【问题标题】:Correct way to pass a struct to pthread within a for loop在 for 循环中将结构传递给 pthread 的正确方法
【发布时间】:2015-01-29 00:37:26
【问题描述】:

1.问题:我需要将一个包含两个整数的结构传递给 pthread_create 调用。

这是在计算结构值的 for 循环中。理想情况下,我希望每个线程使用不同的结构调用 updatePlates()。

2。问题:我创建了结构 {1,2},{3,4},{5,6},但是当线程开始工作时,它们都具有 {5,6} 的值。我的不正确理解 Tuple t; 是每次循环迭代的一个新的临时变量。但是我的调试语句cout<< "t: " << &t << endl; 显示它们在每个循环中都有相同的内存地址。

3.真正的问题:创建“新”结构并将其传递给具有唯一非共享值的每个线程的正确方法是什么?

pthread_t updateThreads[THREADS];
for(size_t i = 0; i < THREADS; ++i)
{
    Tuple t;
    t.start = 1 + (i * increment);
    t.end = t.start + increment -1;
    // Debug Statements //
    cout << "start: " << t.start <<endl;
    cout << "end:   " << t.end <<endl;
    cout << "t:     " << &t <<endl;
    // End Debug //
    returnCode = pthread_create(&updateThreads[i], NULL, updatePlates, (void *)&t);
}
for(size_t i = 0; i < THREADS; ++i)
{
    pthread_join(updateThreads[i], NULL);
}

【问题讨论】:

标签: c++ multithreading struct pthreads


【解决方案1】:

在堆上分配它们

Tuple* t = new Tuple;

赋值

t->start = 1 + (i * increment);
t->end = t->start + increment -1;

传递给pthread_create

returnCode = pthread_create(&updateThreads[i], NULL, updatePlates, (void *)t);

然后在updatePlates 中释放元组。

void* updatePlates(void* data)
{
    Tuple* t = (Tuple*)data;

    // do stuff

    delete t;
    return NULL;
}

或者,当您知道您有多少线程时,您可以定义一个 Tuples 数组并将索引传递到数组中以调用 pthread_create。但请确保数组在线程函数的生命周期内保持在范围内。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-14
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多