在线程之间划分工作? (并行线程)

时间:2016-05-08 21:16:54

标签: c pthreads posix

我正在创建一个程序来对学校项目的某些数字进行一些数学计算。假设我有10个线程但需要处理42个项目,我希望它们能够均匀地处理所有项目并承担大量工作。我使用POSIX pthread库,我知道它与互斥锁有关,但我并不完全确定。

以下是我正在做的事情的简化示例,但我想平衡工作量。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int numbers = { 1, 78, 19, 49, 14, 1, 14. 19, 57, 15, 95, 19, 591, 591 };

void* method() {
  for(size_t i = 0; i < 14; i++) {
    printf("%d\n", (numbers[i] * 2));
  }
}

int main(int argc, char const *argv[]) {
  pthread_t th[10];
  for (size_t i = 0; i < 10; i++) {
    pthread_create(&th[i], NULL, method, NULL);
  }
  return 0;
}

2 个答案:

答案 0 :(得分:1)

如果您提前知道(即,在启动线程之前)需要处理多少项,您只需要在线程中对它们进行分区。例如,告诉第一个线程处理项目0-9,接下来处理10-19,或者其他任何内容。

答案 1 :(得分:1)

您希望每个线程处理表中的给定索引。只要在线程之间正确划分工作,就不必使用互斥锁来保护表,这样它们就不会竞争相同的数据。

一个想法:

/* this structure will wrap all thread's data */
struct work
{
    size_t start, end;
    pthread_t     tid;
};

void* method(void*);
#define IDX_N 42 /* in this example */
int main(int argc, char const *argv[])
{
  struct work w[10];
  size_t idx_start, idx_end, idx_n = IDX_N / 10;
  idx_start = 0;
  idx_end = idx_start + idx_n;
  for (size_t i = 0; i < 10; i++)
  {
    w[i].start = idx_start; /* starting index */
    w[i].end = idx_end;   /* ending index */
    /* pass the information about starting and ending point for each
     * thread by pointing it's argument to appropriate work struct */
    pthread_create(&w[i], NULL, method, (void*)&work[i]);
    idx_start = idx_end;
    idx_end = (idx_end + idx_n < IDX_N ? idx_end + idx_n : IDX_N);
  }
  return 0;
}
void*
method(void* arg)
{
  struct work *w = (struct work* arg);
  /* now each thread can learn where it should start and stop
   * by examining indices that were passed to it in argument */
  for(size_t i = w->start; i < w->end; i++)
    printf("%d\n", (numbers[i] * 2));
  return NULL;
}

有关更复杂的示例,您可以查看thisthis

相关问题