【发布时间】:2015-02-04 13:13:44
【问题描述】:
我正在使用 pthread 用 C 语言实现并行代码。现在我正在尝试使用互斥锁对特定数据结构进行混合操作。例如,我有一个 5,00,000 的数据集,我使用了 4 个线程插入到结构中,并使用了 4 个线程从其中并行删除(整个数据)。只有在 4 个插入线程完成了要插入的数据的至少 30-50% 部分后,我才需要启动 4 个删除线程。是否可以延迟线程? pthreads的条件格式可以用于相同的吗?如果提供任何导致相同的资源将是有用的。
示例代码:
thds = (pthread_t *)malloc((nthdsIns + nthdsDel - 1) * sizeof(pthread_t));
thdArg = (tArg *)malloc((nthdsIns + nthdsDel - 1) * sizeof(tArg));
for(i = 0; i < nthdsIns; i++){
thdArg[i].num = numsIns; // array of elements to be inserted
thdArg[i].start = i * iterIns; //starting index
if(nthdsIns == 1)
thdArg[i].end = nValIns-1; //ending index
else
thdArg[i].end = (i+1) * iterIns - 1;
}
for(k=0; k < nthdsIns; k++)
pthread_create(&thds[k], NULL, pThdIns, &thdArg[k]);//spawning threads
temp = k;
/*Need to put some condition here inorder to allow the insertion threads to complete half of the insertion part*/
for(j = i, k = 0; k < nthdsDel; j++, k++){
thdArg[j].num = numsDel;//array for deletion
thdArg[j].start = k * iterIns;
thdArg[j].end = (k+1) * iterIns - 1;
}
for(k = 0, j = temp; k < nthdsDel; k++, j++)
pthread_create(&thds[j], NULL, pThdDel, &thdArg[j]);//spawning threads
for(i=0; i < (nthdsIns + nthdsDel); i++)
pthread_join(thds[i], NULL);//joining threads
【问题讨论】:
-
SO 的思想是解决特定的编码问题。一个好的问题应该由一个显示后者的例子来支持。通用教程可以在书籍或网络中找到。
-
@alk,我正在对并发跳过列表进行编码,所以在这种情况下,我遇到了分段错误的问题,因为删除函数在循环中继续检查元素大量时间。所以我在想,是否可以先输入一些元素,然后再进行删除
-
那么为什么不给我们展示一个你实际编码的例子呢?
-
@alk,是否将在插入期间自动递增的计数器(使用 __sync_fetch_and_add())放在上面注释的代码区域中以满足问题?
标签: c parallel-processing pthreads