1. 程式人生 > >一個很奇葩的併發單鏈表,不知道為什麼,併發執行緒上1000就會報錯(500以內就很正常)

一個很奇葩的併發單鏈表,不知道為什麼,併發執行緒上1000就會報錯(500以內就很正常)

貼程式碼,如果有知道原因的高手希望可以告訴我一下,謝謝

#include <mutex>//互斥鎖 #include <stdio.h>      #include <string>      #include <WINSOCK2.H>  #include <fstream>  #include <regex> #include <vector> #include <iostream>     #include <thread>//併發的標頭檔案 #include <math.h>//取整的標頭檔案 #pragma comment(lib, "ws2_32.lib") using namespace std;//不加這段名稱空間,就會報錯cout和endl未聲                     //①定義連結串列資料結構  

struct node {     int num;     string data;     struct node *prior;//上一個     struct node *next;//下一個     struct node *end;//最後一個     struct node *px;//返回某個節點,存放於head下,平時可以當這個指標不存在     int lock; }; struct node head;

mutex LISTLOCK;//新建互斥鎖

int CreatEnd(struct node *head) {     struct node *p1,*p2;     p1 = new node;     p1->next = NULL;     if (head->next == NULL)     {         head->next = p1;         head->num = 1;     }     else     {         p2 = head;         while (1)         {             if (p2->next == NULL) break;             p2 = p2->next;         }         p2->next = p1;         head->num++;     }     return 1; }

int DeleteBegin(struct node *head) {     struct node *p1, *p2;     if (head->next == NULL)     {         cout << "節點為空!" << endl;     }     else     {         p1 = p2 = head;         p1 = p1->next;         p2 = p2->next;    p2 = p2->next;         head->next = p2;         delete p1;         head->num--;     }          return 1; }

int CS1() {     int i;     struct node *p1, *p2;     while (1)     {         LISTLOCK.lock();         i = 0;         while (1)         {             if (head.num < 2000)             {                 if (i == 10) break;                 CreatEnd(&head);                 p1 = &head;                 while (1)                 {                     if (p1->next == NULL) break;                     p1 = p1->next;                 }                 p1->num = i;                 i++;             }             else             {                 Sleep(10);                 break;             }         }         cout << head.num << endl;         LISTLOCK.unlock();     }     return 1; }

int CS2() {     struct node *p1;     while (1)     {         LISTLOCK.lock();         p1 = head.next;         while (1)         {             if (head.next == NULL) break;             DeleteBegin(&head);         }         LISTLOCK.unlock();     }          return 1; }

int main() {          int i;     head.num = 0;     head.lock = 0;     head.next = NULL;     i = 0;     while (1)     {         if (i == 1000) break;//這裡改成499就是正常的         std::thread t1(CS1);         //t.join(); // 沒有這句話,會Debug Error的         t1.detach();//不等待執行緒結束

        std::thread t2(CS2);         //t.join(); // 沒有這句話,會Debug Error的         t2.detach();//不等待執行緒結束         i++;     }     getchar();     return 1; }