gpt4 book ai didi

c - 对由 pthread_create() 引起的简单段错误失去了理智

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:13 24 4
gpt4 key购买 nike

在这段代码中,我试图创建一个线程数组。我已将 pthreads 值设置为 1。在 for 循环中,打印了地址、ID 和“已创建”,但该函数似乎从未执行过,因为我没有打印。

段错误实际上发生在底部的 pthread_join 处,但它肯定是由创建引起的,因为该函数从未运行过,对吧? producers[0] 是唯一的线程,因为我只是在测试 1。create 函数像预期的那样传递一个(ID 地址、NULL、void * function() 和 void* 参数)。它必须是显而易见的,但我已经尝试弄清楚了很长时间,我很空虚。

typedef struct ThreadStruct {
int threadIndex;

} ThreadStruct;


void *producer(void* ts){
printf("in producer\n");
FILE* inputfp = threadstruct->inputFiles[0];

hostname = (char*)malloc((MAXNAME+1)*sizeof(char));
while(fscanf(inputfp, hostname) > 0){
printf("%s",hostname);
}

return 0;
}

int main(int argc, char *argv[]){

int pthreads = atoi(argv[1]); //always 1
ThreadStruct threadstruct;
pthread_t producers[pthreads];

for(int i=0;i<pthreads;i++){

printf("in pthread loop\n");
printf("%p \n",&producers[i]);
printf("%ld \n",producers[i]);
pthread_create(&producers[i], NULL, producer, (void *) &threadstruct);
}
pthread_join(producers[0], NULL);
}

最佳答案

您的代码在我这边有效,不会产生段错误。这是打印出来的信息:

$ ./pthread
in pthread loop
0xffffcb70
6444554784
in pthread loop
in producer
0xffffcb78
64
in pthread loop
in producer
0xffffcb80
1
in pthread loop
in producer
0xffffcb88
4299166064
in pthread loop
in producer
0xffffcb90
6443761969
in pthread loop
in producer
0xffffcb98
6445451520
in pthread loop
in producer
0xffffcba0
314761761601
in producer
exit main thread

您的代码在这里:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

typedef struct ThreadStruct {
int threadIndex;

} ThreadStruct;


void *producer(void* ts){
printf("in producer\n");
return 0;
}

int main(int argc, char *argv[]){
int pthreads = 7;
ThreadStruct threadstruct;
pthread_t producers[pthreads];

for(int i=0;i<pthreads;i++){

printf("in pthread loop\n");
printf("%p \n",&producers[i]);
printf("%ld \n",producers[i]);
pthread_create(&producers[i], NULL, producer, (void *) &threadstruct);
}
pthread_join(producers[0], NULL);

printf("exit main thread\n");
}

关于c - 对由 pthread_create() 引起的简单段错误失去了理智,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52980560/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com