【发布时间】:2021-09-12 07:25:41
【问题描述】:
我正在尝试创建一个程序来解决使用 posix 线程就餐哲学家的问题。但是,我一开始就卡住了,因为 std :: cout
pthread_mutex_t mutexSpoon[PHILOSOPHERS];
pthread_t createThread(int number){
pthread_t id;
int rc = pthread_create(&id, NULL, philFunc, &number);
if(rc){
abort();
}
return id;
}
void *philFunc(void *arg){
srand(time(0));
int id = *(int*)arg;
int leftSpoon = (id>0) ? id-1 : PHILOSOPHERS;
int rightSpoon = id;
int temp;
int i = 0;
while(i < 10){
usleep((200 - 50) * ( (double)rand() / RAND_MAX ) + 50);
std::cout << id+1 << " PHILOSOPHER: thinking" << std::endl; ++i;
}
return nullptr;
}
main.cpp
using namespace std;
extern pthread_mutex_t mutexSpoon[PHILOSOPHERS];
int main(){
setlocale(LC_ALL, "rus");
for(int i = 0; i < PHILOSOPHERS; ++i)
pthread_mutex_init(&mutexSpoon[i], NULL);
vector<pthread_t> vecID(PHILOSOPHERS);
for(int i = 0; i < PHILOSOPHERS; ++i)
vecID[i] = createThread(i);
for(int i = 0; i < PHILOSOPHERS; ++i)
pthread_join(vecID[i], NULL);
for(int i = 0; i < PHILOSOPHERS; ++i)
pthread_mutex_destroy(&mutexSpoon[i]);
return 0;
}
【问题讨论】:
-
在
pthread_create(&id, NULL, philFunc, &number);中,您传递的是局部变量的地址。很可能线程只有在createThread返回后才读取变量,然后&number成为悬空指针。 -
你很可能不想在你的线程函数中使用
srand(time(0));。您通常应该在程序开始时在main中调用一次。 -
您可能希望C++ thread support library 比 p-threads 更便携。
-
请注意
rand可能不是线程安全的:stackoverflow.com/questions/6161322/… -
您可能错过了使用
mutexSpoon的行,prehistoricpenguin 想指出这一点
标签: c++ multithreading pthreads