Skip to content

Instantly share code, notes, and snippets.

@leon123858
Created September 4, 2021 08:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leon123858/5d5035b0817c6f5feb16dab1421f84b8 to your computer and use it in GitHub Desktop.
Save leon123858/5d5035b0817c6f5feb16dab1421f84b8 to your computer and use it in GitHub Desktop.
stack use lock
#include <iostream>
#include <atomic>
#include <thread>
#include <mutex>
#define THREAD_N 100
#define ELEMENT_N 1000
using namespace std;
static atomic_int inserts = 0;
static atomic_int deletes = 0;
mutex glock;
class node {
public:
node* next;
int value;
node(int value) {
this->value = value;
next = nullptr;
inserts.fetch_add(1);
}
};
class stack {
public:
node* head;
stack() {
head = NULL;
}
node* getHead() {
return head;
}
void pushNode(int value) {
glock.lock();
node* n = new node(value);
n->next = head;
head = n;
glock.unlock();
}
void popNode() {
start:
if (head == nullptr)
goto start; //一定要刪到, 不放棄
glock.lock();
head = head->next;
glock.unlock();
deletes.fetch_add(1);
}
~stack() {
node* delPtr;
for (node* ptr = this->getHead(); ptr;)
{
delPtr = ptr;
ptr = ptr->next;
delete delPtr;
}
}
};
static atomic <int> insertCount = 0;
void insertNode(stack* stack) {
for (int i = 0; i < ELEMENT_N; i++) {
stack->pushNode(insertCount.fetch_add(1));
}
}
void deleteNode(stack* stack) {
for (int i = 0; i < ELEMENT_N; i++) {
stack->popNode();
}
}
int main()
{
std::cout << "Start!\n";
stack* testStack = new stack();
thread threads_insert[THREAD_N];
thread threads_delete[THREAD_N];
for (int i = 0; i < THREAD_N; i++) {
threads_insert[i] = thread(insertNode, testStack);
}
for (int i = 0; i < THREAD_N; i++) {
threads_delete[i] = thread(deleteNode, testStack);
}
for (int i = 0; i < THREAD_N; i++) {
threads_insert[i].join();
threads_delete[i].join();
}
int count = 0;
cout << "finally" << endl;
for (node* ptr = testStack->getHead(); ptr; ptr = ptr->next)
count++;
delete testStack;
cout << "inserts:" << atomic_load(&inserts) << " count" << count << endl;
cout << "delete: " << atomic_load(&deletes) << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment