所以我有一个在 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;
}
Run Code Online (Sandbox Code Playgroud)
您可以通过多种方式执行此操作,最简单的一种是传递一些有意义的值作为线程参数来标识每个线程。
下面是一个例子:
void *request(void *data)
{
const int id = *(const int *)data;
int ii;
for(ii = 0; ii < 8; ii++)
{
sleep(1);
printf("REQUEST FROM LIFT %d COMPLETED\n", id);
}
}
int main()
{
const int id1 = 1, id2 = 2, id3 = 3;
pthread_t lift1;
pthread_t lift2;
pthread_t lift3;
pthread_create(&lift1, NULL, request, (void *)&id1);
pthread_create(&lift2, NULL, request, (void *)&id2);
pthread_create(&lift3, NULL, request, (void *)&id3);
pthread_join(lift1, NULL);
pthread_join(lift2, NULL);
pthread_join(lift3, NULL);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您还可以将这些变量定义id为static全局变量:
// Outside main:
static const int id1 = 1, id2 = 2, id3 = 3;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
83 次 |
| 最近记录: |