【发布时间】:2016-01-28 13:23:11
【问题描述】:
我正在解决一个大学练习题。父进程通过管道将在文件中读取的数字 (nThreads) 提供给子进程。子进程必须执行 nThreads 个线程并休眠 nThreads 秒,每个线程必须打印子进程给定的随机数并休眠该随机数秒。 进程打印一切正常,但线程没有。我的代码有什么问题?
...
#include <pthread.h>
void exitError() {
write(2, "Error!\n", 7);
exit(1);
}
void *doThread(void* args) {
long rnd = (long)args;
printf("Random number = %ld", rnd);
sleep(rnd);
pthread_exit((void *)0);
}
int main (int argc, const char * argv[]) {
int pid, n, piped[2];
pipe(piped);
if ((pid=fork()) == -1) {
write(1, "Error!\n", 4);
exit(1);
}
else if (pid == 0) { //son
int nThreads;
close(piped[1]);
read(piped[0], &nThreads, 2);
printf("\nI have to create %d threads\n\n", nThreads);
pthread_t *threads;
threads = (pthread_t *) malloc(nThreads*sizeof(pthread_t));
int random;
random = rand();
pthread_create(&threads[nThreads], NULL, doThread, random);
sleep(nThreads);
exit(0);
}
else { //father
signal(SIGALRM, exitError);
alarm(10);
if (argc != 2) {
write(1, "Command error!\n", 24);
}
int fd = open(argv[1], O_RDONLY);
char buf[1];
n = read(fd, buf, 1);
int nThreads = atoi(buf);
printf("I say %d to my son\n", nThreads);
close(piped[0]);
write(piped[1], &nThreads, 2);
wait(NULL);
alarm(0);
exit(0);
}
return 0;
}
如果我做错了什么,请原谅我,这是我第一次在这里提出问题。
【问题讨论】:
-
你需要
pthread_join()你的线程。 -
int* random; *random = ...是错误的。致命错误。 -
对不起,你是对的。我修复了它,但线程似乎仍然不起作用。
-
除非您使用的是旧的 16 位系统,否则
sizeof(int)(或sizeof(nThreads))不等于2。 -
@Pottercomuneo:您对
int *问题的“修复”当然是不正确的。您似乎不确定是int、long还是long*。这些东西是不可互换的。此外,您仍然不使用您的线程pthread_join(),因此您正在加速进程终止,并且它可能会在random()(或&random,如案件目前)。
标签: c multithreading pthreads