Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/google-apps-script/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C pthread_join给定分段错误_C - Fatal编程技术网

C pthread_join给定分段错误

C pthread_join给定分段错误,c,C,不知何故,我的代码返回了分段错误。sockfd是一个int或文件描述符 pthread_t tid[4]; int err; int k = 0; while (k < 4) { err = pthread_create(&tid[k], NULL, listen_connection, (void*) sockfd); k++; } pthread_join(tid[0], NULL); // causes segmentation fault pthread_j

不知何故,我的代码返回了分段错误。sockfd是一个int或文件描述符

pthread_t tid[4];
int err;
int k = 0;
while (k < 4) {
    err = pthread_create(&tid[k], NULL, listen_connection, (void*) sockfd);
    k++;
}
pthread_join(tid[0], NULL); // causes segmentation fault
pthread_join(tid[1], NULL);
pthread_join(tid[2], NULL);
pthread_join(tid[3], NULL);

return 0;
实际功能:

void * listen_connection(void *sockfd) {

int newsockfd, n;
// client address
struct sockaddr_in cli_addr;
socklen_t clilen;

newsockfd = accept(*(int*)sockfd, (struct sockaddr *) &cli_addr, &clilen);
...
编辑:我想出来了

而不是:

err = pthread_create(&tid[k], NULL, listen_connection, (void*) sockfd);
我把它改成:

err = pthread_create(&tid[k], NULL, listen_connection, (void*) &sockfd);

*int*sockfd是错误的。sockfd不是指针,因为您向pthread_create传递了一个int。将&sockfd传递给pthread\u create,或者像int-sockfd那样强制转换。

分段错误不太可能是由pthread\u join引起的。手册页pthread_join函数等待线程指定的线程终止,并且线程指定的线程必须是可连接的


我认为您应该检查pthread_jointid[0]的返回值,NULL;声明,以确保其按预期工作。它应该给出一个错误号,因为您的线程tid[4]不可连接。您应该创建pthread属性变量pthread\u attr\u t attr;然后初始化attr变量pthread_attr_init&attr;最后使用pthread\u attr\u setdetachstate&attr,pthread\u CREATE\u JOINABLE;。您应该使用这个属性变量创建线程。

如何确切地知道pthread_jointid[0],NULL;是什么导致了故障?你使用了调试器吗?还有,你为什么不能使用for循环?我不太确定,但是如果我注释掉所有pthread_连接行,那么就没有分段错误。这不是我回答的问题吗?弄清楚如何终止线程可能也会有帮助。默认情况下,新线程是在可连接状态下创建的。所以不需要显式地设置它。
err = pthread_create(&tid[k], NULL, listen_connection, (void*) &sockfd);