【发布时间】:2016-03-30 01:07:54
【问题描述】:
我正在尝试进入线程世界,但遇到了一些麻烦。下面的代码每隔一段时间就会运行一次,但似乎是完全随机的。给它相同的输入总是给我不同的结果,我很困惑。 有时 PrintHello() 打印出参数,有时它打印垃圾,有时它只是段错误。
#define NUM_THREADS 5
char *prompt = "% ";
struct thread_data{
int thread_id;
//int sum;
char *message;
};
void *PrintHello(void *threadarg)
{
struct thread_data *local_data;
local_data = (struct thread_data *) threadarg;
int taskid = local_data->thread_id;
const char *arguments = local_data->message;
fprintf(stderr, "Hello World! It's me, thread %s!\n", arguments);
pthread_exit(NULL);
}
PrintHello() 是我认为问题所在。
int main()
{
int pid;
//int child_pid;
char line[81];
char *token;
char *separator = " \t\n";
char **args;
char **args2;
char *hp;
char *cp;
char *ofile;
int i;
int j, h, t, rc;
args = malloc(80 * sizeof(char *));
args2 = malloc(80 * sizeof(char *));
signal(SIGINT, SIG_IGN);
while (1) {
fprintf(stderr, "%s", prompt);
fflush(stderr);
if (fgets(line, 80, stdin) == NULL)
break;
/* get rid of the '\n' from fgets */
if (line[strlen(line) - 1] == '\n'){
line[strlen(line) - 1] = '\0';
}
// split up the line
i = 0;
while (1) {
token = strtok((i == 0) ? line : NULL, separator);
if (token == NULL)
break;
args[i++] = token;
}
args[i] = NULL;
ofile = args[i-1];
printf("%s\n", ofile);
上面的东西只是对输入进行标记并且工作正常。
struct thread_data thread_data_array[i];
pthread_t threads[i];
for(t=0; t<i; t++){
thread_data_array[t].thread_id = t;
thread_data_array[t].message = args[t];
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)&thread_data_array[t]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
}
}
【问题讨论】:
-
您需要主线程等待所有子线程退出后才退出。当主线程退出时,所有子线程也会被杀死。在主线程中为每个子线程调用
pthread_join。 -
@kaylum 哇,好用! pthread_join 似乎已经解决了所有问题,谢谢。
-
如果线程在
main返回后启动,您期望会发生什么?然后参数指向一个已被销毁的对象。
标签: c multithreading arguments posix