如何知道哪个线程正在执行一个函数

问题描述 投票:1回答:1

因此,我有一个电梯程序的缩减版本,该程序在c中使用pthreads。每个线程都是调用函数request()的单独提升。我不确定如何知道哪个提升(1、2或3)是线程正在使用该功能请求。在request函数中,我需要打印当时使用哪个线程。抱歉,如果我的解释不完整。

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;
}
c pthreads
1个回答
1
投票

您可以通过多种方式执行此操作,最简单的方法是传递一些有意义的值作为线程参数来标识每个线程。

这里是一个例子:

void* request(void *data)
{ 
    int id = *(int*)data;
    int ii;

    for(ii = 0; ii < 8; ii++)
    {
        sleep(1);
        printf("REQUEST FROM LIFT %d COMPLETED\n", my_id);
    }
}

int main()
{
    int id1 = 1, id2 = 2, id3 = 3;
    pthread_t lift1;
    pthread_t lift2;
    pthread_t lift3;

    pthread_create(&lift1, NULL, request, &id1);
    pthread_create(&lift2, NULL, request, &id2);
    pthread_create(&lift3, NULL, request, &id3);

    pthread_join(lift1, NULL);
    pthread_join(lift1, NULL);
    pthread_join(lift1, NULL);

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.