64,648
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <windows.h>
using namespace std;
struct Node
{
Node *next;
int data;
};
struct List
{
Node *head;
HANDLE mutex;
};
List *CreateList()
{
List *list = new List;
list->head = NULL;
list->mutex = CreateMutex(NULL, FALSE, NULL);
return list;
}
void AddNode(List *list, Node* node)
{
WaitForSingleObject(list->mutex, INFINITE);
node->next = list->head;
list->head = node;
ReleaseMutex(list->mutex);
}
void SwapList(List* &list1, List *&list2)
{
List *temp = NULL;
HANDLE handArry[2];
handArry[0] = list1->mutex;
handArry[1] = list1->mutex;
WaitForMultipleObjects(2, handArry, TRUE, INFINITE);
temp->head = list1->head;
list1->head = list2->head;
list2->head = temp->head;
ReleaseMutex(handArry[0]);
ReleaseMutex(handArry[0]);
}
int main()
{
List *list1 = CreateList();
List *list2 = CreateList();
Node *node1 = new Node;
node1->data = 1;
node1->next = NULL;
AddNode(list1, node1);
Node *node2 = new Node;
node2->data = 2;
node2->next = NULL;
AddNode(list2, node2);
SwapList(list1, list2);
cout << list1->head->data;
}
#include <iostream>
#include <windows.h>
using namespace std;
struct Node
{
Node *next;
int data;
};
struct List
{
Node *head;
HANDLE mutex;
};
List *CreateList()
{
List *list = new List;
list->head = NULL;
list->mutex = CreateMutex(NULL, FALSE, NULL);
return list;
}
void AddNode(List *list, Node* node)
{
WaitForSingleObject(list->mutex, INFINITE);
node->next = list->head;
list->head = node;
ReleaseMutex(list->mutex);
}
void SwapList(List* &list1, List *&list2)
{
List *temp = NULL;//Node *temp;
HANDLE handArry[2];
handArry[0] = list1->mutex;
handArry[1] = list1->mutex;
WaitForMultipleObjects(2, handArry, TRUE, INFINITE);
temp = list1->head;//mark
list1->head = list2->head;
list2->head = temp;//mark
ReleaseMutex(handArry[0]);
ReleaseMutex(handArry[1]);
}
int main()
{
List *list1 = CreateList();
List *list2 = CreateList();
Node *node1 = new Node;
node1->data = 1;
node1->next = NULL;
AddNode(list1, node1);
Node *node2 = new Node;
node2->data = 2;
node2->next = NULL;
AddNode(list2, node2);
SwapList(list1, list2);
cout << list1->head->data;
}