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

So I have a scaled down version of an elevator program that uses pthreads in c. Each thread is an individual lift that calls function request(). I am not sure how to know which lift (1, 2 or 3) which are threads are using the function request. In the request function I need to print which thread used it at that time. Sorry if my explanation doesn't make complete sense.

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;
}
评论
  • 诺吟怀
    诺吟怀 回复

    您可以使用pthread_self()方法来了解当前线程ID,这将有助于您识别线程之间。

    printf("thread id = %d\n", pthread_self()); 
    
  • Mr糖
    Mr糖 回复

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

    这是一个例子:

    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, &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;
    }