我正在尝试使用带线程的基于时间的池化系统。我设法使用fork()实现了这一点,现在我正尝试使用线程来实现它。计时器线程似乎工作正常,但是由于某些原因,我无法将char *数组传递给线程(转储核心)。
注意:如果尝试退出状态为0的线程,则不会收到有关将整数赋予返回void *的函数的警告。但是,当我尝试返回其他内容时,将其设置为1,则会收到警告。我试图将它们转换为void *,但没有任何影响。
现在,输入一些代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define COUNTING_SUCCESS 0
#define POOLING_SUCCESS 1
int size = 3;
void *count(void *bound_arg){
int index = 0;
int *bound = (int*)bound_arg;
printf("Counting started...\n");
while(index < *bound){
printf("You have %d seconds left\n",*bound - index);
sleep(1);
index++;
}
printf("Time's up!\n");
pthread_exit(COUNTING_SUCCESS);
}
void *pool(void *questions_ptr){
char *questions = (char*)questions_ptr;
char *answer = calloc(sizeof(char*)*size,size);
for(int i =0 ; i < size ; i++){
printf("%s : ",questions[i]);
scanf("%s",&answer);
}
pthread_exit(0);
}
int main(){
char* questions[] = {"Q1","Q2","Q3"};
int limit = 3 ;
int *countingLimit = &limit;
void *countingStatus;
void *poolingStatus;
pthread_t timerThread;
int threadID = pthread_create(&timerThread,NULL,count,(void*)countingLimit);
pthread_join(timerThread,&countingStatus);
printf("%d\n",(int*)countingStatus);
pthread_t poolingThread;
int poolingThreadID = pthread_create(&poolingThread,NULL,pool,(void*)questions);
pthread_join(poolingThread,&poolingStatus);
printf("%d\n",(int*)poolingStatus);
}
示例输出:
Counting started...
You have 3 seconds left
You have 2 seconds left
You have 1 seconds left
Time's up!
0
Segmentation fault (core dumped) //this is where i try to pass the char*
我无法进入该功能。
P.S。我正在使用以下命令构建可执行文件:
gcc -o pool pool.c -pthread
答案 0 :(得分:1)
这与线程无关。您要将单个if __name__ == '__main__'
传递给printf,它期望char
(用于字符串)在哪里,所以它崩溃了:
char *
您已将printf("%s : ",questions[i]);
声明为quesstions
(单个字符串),因此您要获取一个char *
,然后将其作为printf的虚假指针并崩溃
您可能打算将char
声明为questions
,因为这就是您作为pthread参数传递的内容:
char **