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

劳斯莱斯(JustLloyd)

我正在创建一个程序,以便为一个学校项目的一些数字做一些数学运算。假设我有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;
}
4个

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

一个主意:

/* 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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

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

来自分类Dev

对于C#中的MultiClient TCP服务器,如何在线程之间划分工作?

来自分类Dev

使用pthread库在线程之间进行同步

来自分类Dev

在线程之间传递对象

来自分类Dev

在线程之间移动向量

来自分类Dev

在线程之间共享mvar

来自分类Dev

在线程之间共享容器阵列

来自分类Dev

在线程之间共享变量的方法

来自分类Dev

C ++-在线程之间传递数据

来自分类Dev

在线程之间分配不均数

来自分类Dev

在线程之间传输函数调用

来自分类Dev

在线程之间发送盒装特征

来自分类Dev

pthreads在线程之间共享内存

来自分类Dev

在线程之间传递对象

来自分类Dev

在线程之间传递NSManagedObjectContext

来自分类Dev

工作共享机制(在OpenMP中)是否在线程正在执行时在线程之间传输任务?

来自分类Dev

多线程问题-在线程之间传递对象

来自分类Dev

划分工作表值

来自分类Dev

在固定数量的线程之间划分数组

来自分类Dev

flask会话变量是否在线程之间保持状态?

来自分类Dev

如何在线程之间发送变量/信息

来自分类Dev

使用Android Realm在线程之间进行读写

来自分类Dev

HINSTANCE在线程之间有效吗?

来自分类Dev

C ++在线程之间共享状态的最佳方法

来自分类Dev

如何在线程之间共享对AtomicBool的访问?

来自分类Dev

通过eventfd在线程之间传输数据

来自分类Dev

在线程之间共享对象的最佳方法?

来自分类Dev

不确定如何在线程之间传递对象

来自分类Dev

在线程之间传递可变数据