贴代码,如果有知道原因的高手希望可以告诉我一下,谢谢
#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;
}