【发布时间】:2016-11-17 17:46:55
【问题描述】:
我正在从事一个涉及多线程的项目。虽然我对多线程有相当的了解,但我没有写过很多这样的代码。以下代码只是我为动手编写的一个简单代码。使用 gcc -pthread 编译时效果很好。
要在此代码的基础上进行构建,我需要包含一些已经包含并链接了 pthread 的库。如果我通过包含和链接这些库进行编译,则 5 次中有 3 次会出现分段错误。 main() 中的第一个 for 循环存在一些问题——用多个语句替换这个 for 循环就可以了。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 3
pthread_mutex_t m_lock = PTHREAD_MUTEX_INITIALIZER;
typedef struct{
int id;
char ip[20];
} thread_data;
void *doOperation(void* ctx)
{
pthread_mutex_lock(&m_lock);
thread_data *m_ctx = (thread_data *)ctx;
printf("Reached here\n");
pthread_mutex_unlock(&m_lock);
pthread_exit(NULL);
}
int main()
{
thread_data ctx[NUM_THREADS];
pthread_t threads[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; ++i)
{
char ip_n[] = "127.0.0.";
char ip_h[4];
sprintf(ip_h, "%d", i+1);
strcpy(ctx[i].ip, strcat(ip_n, ip_h));
}
for (int i = 0; i < NUM_THREADS; ++i)
{
pthread_create(&threads[i], NULL, doOperation, (void *)&ctx[i])
}
for (int i = 0; i < NUM_THREADS; ++i)
{
pthread_join(threads[i], NULL);
}
pthread_exit(NULL);
}
【问题讨论】:
-
strcat(ip_n, ip_h)- 调用 未定义的行为,除非ip_h没有内容。 -
但是 ip_h 确实有内容——(i+1) 的字符串版本。如果 i 为 0,我的意思是“1”。
-
@SonuMishra,是的,这就是问题所在。
-
一般来说,在调试分段错误(和一般的错误)时,调试器非常有用。看看 gdb - 周围有很多教程:google.com/search?q=gdb%20tutorial
标签: c multithreading segmentation-fault