【发布时间】:2016-10-29 00:57:17
【问题描述】:
我正在制作一个模拟一部电梯和 49 个人的多线程程序,每个人都有自己的线程和电梯。我正处于开始阶段,只是试图创建线程并验证它们是否正常工作。
我有一个名为person_threads 的pthread 数组,我试图在for 循环中对其进行初始化,在循环中我发送一条带有线程号的消息并在线程中打印出来。出于某种原因,我得到了奇怪的行为,几乎就像 for 循环在创建一些线程之前没有正确迭代(请参阅循环和输出)。每次运行时,这种行为都是随机的并且是多种多样的,我不确定我需要做什么才能正确创建线程。如果您对可能导致此问题的原因有任何见解,请提供帮助。
代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define MAX_PERSONS 49
void *person(void *myvar);
void *elevator(void *myvar);
int main(int argc, char *argv[]){
pthread_t elevator_thread;
pthread_t person_threads[MAX_PERSONS]; //My array of threads
char *elev_msg = "Elevator thread started";
pthread_create(&elevator_thread, NULL, elevator, (void *) elev_msg);
//Here is where I try to initialize messages and threads,
//see Persons function and output
for (int i = 0; i < MAX_PERSONS; i++){
char msg[50];
snprintf(msg, sizeof msg, "Person thread %d started", i);
pthread_create(&person_threads[i], NULL, person, (void *) msg);
}
printf("Main function after pthread_creates\n");
pthread_join(elevator_thread, NULL);
for (int i = 0; i < MAX_PERSONS; i++){
pthread_join(person_threads[i], NULL);
}
return 0;
}
void *person(void *myvar){
char *msg;
msg = (char *) myvar;
printf("%s\n", msg);
return NULL;
}
void *elevator(void *myvar){
char *msg;
msg = (char *) myvar;
printf("%s\n", msg);
return NULL;
}
输出
brendan@brendan-Ubuntu-Desk:~/Documents/OS-Project2$ ./elevator
Elevator thread started
Person thread 7 started
Person thread 7 started
Person thread 7 started
Person thread 7 started
Person thread 7 started
Person thread 7 started
Person thread 7 started
Person thread 8 started
Person thread 9 started
Person thread 10 started
Person thread 12 started
Person thread 12 started
Person thread 14 started
Person thread 15 started
Person thread 15 started
Person thread 16 started
Person thread 17 started
Person thread 18 started
Person thread 19 started
Person thread 20 started
Person thread 21 started
Person thread 22 started
Person thread 23 started
Person thread 24 started
Person thread 25 started
Person thread 26 started
Person thread 27 started
Person thread 28 started
Person thread 29 started
Person thread 30 started
Person thread 31 started
Person thread 32 started
Person thread 33 started
Person thread 34 started
Person thread 35 started
Person thread 36 started
Person thread 37 started
Person thread 38 started
Person thread 39 started
Person thread 40 started
Person thread 41 started
Person thread 42 started
Person thread 43 started
Person thread 44 started
Person thread 45 started
Person thread 46 started
Person thread 47 started
Person thread 48 started
Main function after pthread_creates
Person thread 48 started
请注意如何有多个 7、15、12 和 48。每次运行时,此行为都是随机的。我注意到它实际上总是创建 50 个线程,但我需要正确初始化数组。任何帮助将不胜感激。
【问题讨论】:
标签: c linux multithreading pthreads