从for循环传递线程一个值 [英] Passing threads a value from a for loop

查看:204
本文介绍了从for循环传递线程一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建线程,并向每个线程传递for循环的值.这是代码段

I am attempting to create threads and pass each thread the value from a for loop. Here is the code segment

pthread_t *threadIDs;
    int i = 0;
    if(impl == 1)
    {
        threadIDs = (pthread_t *)malloc(sizeof(pthread_t)*reduces);
        for(;i < reduces; i++)
        {
            pthread_create(&threadIDs[i], NULL, reduce,&i);
        }
    }

它没有传递正确的循环值,这是有道理的,因为我正在创建一个竞争条件.从循环中传递i的正确值的最简单方法是什么?

It is not passing the correct values of the loop, which makes sense since I am creating a race condition. What is the simplest way to pass the correct value of i from my loop?

另一个问题,每个线程会在创建和调用下一个线程之前完成执行吗?

Another question, will each thread finish executing before the next one is created and called?

推荐答案

从循环中传递i的正确值的最简单方法是什么?

What is the simplest way to pass the correct value of i from my loop?

什么被认为是"简单"取决于用例,因此这里提供了另一种解决您所遇到的问题的方法:

What is to be considered "simple" depends on the use case, so here another approach to solve the issues you present:

#include <pthread.h>

pthread_mutex_t m_init;
pthread_cond_t c_init;

int init_done = 1;

void* thread_function(void * pv)
{
  pthread_mutex_lock(&m_init);

  size_t i = *((size_t*) pv);
  init_done = 1;

  pthread_cond_signal(&c_init);

  pthread_mutex_unlock(&m_init);

  ...
}

#define THREADS_MAX (42)

int main(void)
{
  pthread_t thread[THREADS_MAX];

  pthread_mutex_init(&m_init, NULL);
  pthread_cond_init(&c_init, NULL);

  for(size_t i = 0; i < THREADS_MAX; ++i)
  {
    pthread_mutex_lock(&m_init);

    init_done = 0;
    pthread_create(&thread[i], NULL, thread_function, &i);

    while (!init_done)
    {
      pthread_cond_wait(&c_init);
    }

    pthread_mutex_unlock(&m_init);
  }

  ...
}

(为清晰起见,省略了错误检查)

这篇关于从for循环传递线程一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆