我正在创建一个程序,以便为一个学校项目的一些数字做一些数学运算。假设我有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;
}
您希望每个线程处理表中给定的索引。只要您在线程之间正确分配工作,就不必用互斥锁保护表,这样它们就不会争用相同的数据。
一个主意:
/* 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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句