将char*传递给pthread崩溃
我正试图获得一个基于时间的线程池系统。我使用fork()成功地实现了这一点,现在我尝试使用线程实现它。计时器线程似乎工作正常,但由于某些原因,我无法将char*数组传递给线程(转储内核) 注意:如果我尝试退出状态为0的线程,我不会得到关于为返回void*的函数提供整数的警告。但是,当我试图返回其他东西时,让它为1,我会得到一个警告。我试着让它们无效,但没有效果 现在,对于一些代码:将char*传递给pthread崩溃,c,char,pthreads,coredump,C,Char,Pthreads,Coredump,我正试图获得一个基于时间的线程池系统。我使用fork()成功地实现了这一点,现在我尝试使用线程实现它。计时器线程似乎工作正常,但由于某些原因,我无法将char*数组传递给线程(转储内核) 注意:如果我尝试退出状态为0的线程,我不会得到关于为返回void*的函数提供整数的警告。但是,当我试图返回其他东西时,让它为1,我会得到一个警告。我试着让它们无效,但没有效果 现在,对于一些代码: #include <stdio.h> #include <stdlib.h> #inclu
#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);
}
我无法让它进入函数
另外,我正在使用以下方法构建可执行文件:
gcc -o pool pool.c -pthread
这与线程无关。您正在将单个
char
传递给printf,其中它需要char*
(对于字符串),因此它崩溃:
printf("%s : ",questions[i]);
您已将quesstions
声明为char*
(单个字符串),因此您将获取单个char
,然后printf将其视为伪指针并崩溃
您可能打算将questions
声明为char**
,因为这是作为pthread参数传入的内容:
char **questions = (char**)questions_ptr;
char**问题
。您没有收到任何编译器警告吗?gdb
是您的朋友(在本例和其他类似情况下)。-Wall-Wextra-Werror
这不对:printf(“%d\n”,(int*)countingStatus)代码>那么我应该如何获取线程的退出值?我知道它返回空*。你能说得更清楚些吗?
char **questions = (char**)questions_ptr;