问题描述:
这是一段给链表添加节点的函数:
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 头指针是被多个线程共享的