简体   繁体   English

POSIX线程中的唯一值

[英]Unique value within POSIX thread

I am trying to pass into each thread a struct and have each thread print out the value within the struct and show that it is unique per thread. 我试图将每个线程传递给一个结构,并让每个线程打印出结构中的值,并显示每个线程是唯一的。

My problem is that each thread prints out the same value even though i change the value right before passing it in. 我的问题是每个线程打印出相同的值,即使我在传入之前更改了值。

const int NUM_THREADS = 2;

struct number
{
    int uniqueNumber;
};

void* showUniqueNumber(void* numberStruct);

int main()
{
    pthread_t threadID[NUM_THREADS];

    number* numberPtr = new number();

    for(int i=0; i < NUM_THREADS; i++)
    {
        numberPtr->uniqueNumber = i;
        pthread_create(&threadID[i], NULL, showUniqueNumber, (void*)numberPtr);
    }

    for(int i=0; i < 5; i++)
    {
        pthread_join(threadID[i], NULL);
    }

    return 0;
}

void* showUniqueNumber(void* numberStruct)
{
    number* threadPtrN = (number*)numberStruct;

    cout << threadPtrN->uniqueNumber << endl;

    return (void*)0;
}

It's because it's the same object. 这是因为它是同一个对象。 You can do this: 你可以这样做:

pthread_t threadID[NUM_THREADS];
number numbers[NUM_THREADS];

for(int i = 0; i < NUM_THREADS; i++)
{
    numbers[i].uniqueNumber = i;
    pthread_create(&threadID[i], NULL, showUniqueNumber, numbers + i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM