我现在正在上并发类(class),我已经完成了我的第一个(非常简单的)项目,现在我想让它真正有用。
在我的代码中,我在一个数组中对第二个数组的每个值进行二进制搜索。对于第二个数组中的每个值,我生成一个线程。结果证明这比顺序解决方案慢,所以我的想法是我会生成少量线程并在它们每次完成执行时向它们传递一个新 key 。
我有几个问题。第一个问题是,当没有更多键时,如何让线程退出?
如何传递新 key ?
如何让线程在等待新 key 时不使用旧 key 执行(我一直在阅读有关条件等待的内容,并认为这就是我所需要的)。
这是我当前的(无效的)解决方案。
#define ARRAYSIZE 50000
#define KEY_NOT_FOUND -1
#define KEY_FOUND 0
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
int binary_search(int *array, int key, int min, int max);
void *worker(void *arg);
int count = 0;
pthread_mutex_t L;
int l_array[ARRAYSIZE * 2];
int main(void)
{
int r_array[ARRAYSIZE];
int *p;
pthread_t *threads;
int ix = 0;
int jx = 0;
struct timeval start, stop;
double elapsed;
for(ix = 0; ix < ARRAYSIZE; ix++)
{
r_array[ix] = ix;
}
for(ix = 0; ix < ARRAYSIZE * 2; ix++)
{
l_array[ix] = ix + 2;
}
gettimeofday(&start, NULL);
threads = (pthread_t *) malloc(ARRAYSIZE * sizeof(pthread_t));
for (jx = 0; jx < ARRAYSIZE; jx++) {
p = (int *) malloc(sizeof(int));
*p = r_array[jx];
pthread_create(&threads[jx], NULL, worker, (void *)(p));
}
for (jx = 0; jx < ARRAYSIZE; jx++) {
pthread_join(threads[jx], NULL);
}
fprintf(stderr, "%d\n", count);
gettimeofday(&stop, NULL);
elapsed = ((stop.tv_sec - start.tv_sec) * 1000000+(stop.tv_usec-start.tv_usec))/1000000.0;
printf("time taken is %f seconds\n", elapsed);
return 0;
}
void* worker(void *arg)
{
int boolean = 0;
int key = *((int *) arg);
boolean = binary_search(l_array, key, 0, ARRAYSIZE * 2);
if(boolean == 1)
{
pthread_mutex_lock(&L);
count++;
pthread_mutex_unlock(&L);
}
}
int binary_search(int *array, int key, int min, int max)
{
int mid = 0;
if (max < min) return 0;
else
{
mid = (min + max) / 2;
if (array[mid] > key) return binary_search(array, key, min, mid - 1);
else if (array[mid] < key) return binary_search(array, key, mid + 1, max);
else
{
return 1;
}
}
}
最佳答案
注意:下面的代码没有经过测试,但是很简单...
- 将
r_array[]
的基地址传递给 worker - 保持全局
next_index
- 定义另一个
pthread_mutex
PS:与线程数一样,从 2 开始,直到发现吞吐量没有差异为止。您还需要考虑所有的间接费用……
void worker(void *arg)
{
int* r_arrPtr = (int*) arg;
int boolean = 0;
int key =0;[
while (1) {
pthread_mutex_lock(&pNextIndex_MutEx);
if (next_index < ARRAYSIZE) {
key = r_arrPtr[next_index];
next_index ++;
} else {
pthread_mutex_unlock(&pNextIndex_MutEx);
return;
}
pthread_mutex_unlock(&pNextIndex_MutEx);
boolean = binary_search(l_array, key, 0, ARRAYSIZE * 2);
if (boolean == 1) {
// ....
}
}
}
关于c - 更有效的并发解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13146176/