【发布时间】:2020-04-24 14:14:17
【问题描述】:
所以我有一个电梯程序的缩小版本,它在 c 中使用 pthreads。每个线程都是调用函数request() 的单独电梯。我不确定如何知道哪个电梯(1、2 或 3)是线程正在使用函数请求。在请求函数中,我需要打印当时哪个线程使用了它。对不起,如果我的解释不完全有意义。
void* request(void* abc)
{
int ii;
for(ii = 0; ii < 8; ii++)
{
sleep(1);
printf("REQUEST FROM LIFT COMPLETED\n");
}
}
int main()
{
pthread_t lift1;
pthread_t lift2;
pthread_t lift3;
pthread_create(&lift1, NULL, request, NULL);
pthread_create(&lift2, NULL, request, NULL);
pthread_create(&lift3, NULL, request, NULL);
pthread_join(lift1, NULL);
pthread_join(lift1, NULL);
pthread_join(lift1, NULL);
return 0;
}
【问题讨论】:
-
最简单的解决方案是传递除 NULL 以外的其他参数作为
pthread_create()的最后一个参数,因为在您的示例中这将传递给请求函数(如void* abc)。编辑:花费了几秒钟的时间...... Marco Bonelli 发布了我的意思 -
pthread_self()将返回调用线程的pthread_t。一些代码假定pthread_t是一个整数,但这不是可移植的。见How to print pthread_t。