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

问题描述 投票:0回答:2

因此,我有一个电梯程序的缩减版本,该程序在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
2个回答
6
投票

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

这里是一个例子:

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(lift1, NULL);
    pthread_join(lift1, NULL);

    return 0;
}

您还可以将这些id变量定义为static全局变量:

// Outside main:
static const int id1 = 1, id2 = 2, id3 = 3;

-1
投票

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

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", pthread_self());     
    }
}

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.