OpenMP(三)#pragma omp critical

问题描述:

这是一段给链表添加节点的函数:

void addToList(int data)
{
 item_t * newItem = (item_t *) malloc(sizeof(item_t));
 newItem->data = data;
 newItem->next = NULL;

 // Find tail and add newItem to it.
 if(head == NULL) // i.e. list is empty .
 {
    head = newItem;
 }
 else // Find end of list and add to it.
 {
    item_t *tail = head;
    while (tail->next != NULL){
        tail = tail->next;
    }
    tail->next = newItem;
 }
}

并行化调用addToList函数:

#pragma omp parallel for
for(i = 0; i < numAdd; i++){
    addToList ( i );
}

但在运行后发现,一些元素并没有如期加入链表,而是直接丢失了。此外,那些丢失的元素也会占用空间,且这些空间没有被释放。这不满足tread safe的条件。

注意: thread safe不意味着高效率,很多时候都会牺牲效率来成全thread safe。

造成以上问题的原因:

1. *head 头指针是被多个线程共享的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值