gpt4 book ai didi

c - 将 char* 传递给 pthread 崩溃

转载 作者:行者123 更新时间:2023-11-30 21:22:38 25 4
gpt4 key购买 nike

我正在尝试获得一个带有线程的基于时间的池系统。我设法使用 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*

我无法让它进入该功能。

附注我正在使用以下方式构建可执行文件:

gcc -o pool pool.c -pthread

最佳答案

这与线程无关。您将单个 char 传递给 printf,它在哪里期望 char * (对于字符串),因此它崩溃了:

printf("%s : ",questions[i]);

您已将 questions 声明为 char *(单个字符串),因此您将获取单个 char,然后被 printf 视为假指针并崩溃。

您可能打算将 questions 声明为 char **,因为这就是您作为 pthread 参数传递的内容:

char **questions = (char**)questions_ptr;

关于c - 将 char* 传递给 pthread 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52910751/

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