Last active
December 27, 2015 22:39
-
-
Save chuanying/7400509 to your computer and use it in GitHub Desktop.
生产者与消费者(单链表),一个单链表,有个表头和表尾,一个线程作为消费者每次从表头去一个元素,另一个线
程作为生产者每次从表尾加一个元素,不加锁如何实现?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <iostream> | |
#include <sstream> | |
#include <vector> | |
#include <set> | |
#include <list> | |
#include <map> | |
#include <thread> | |
#include <algorithm> | |
#include <stdio.h> | |
#include <math.h> | |
#include <chrono> | |
typedef long long lld; | |
using namespace std; | |
class SingleReadWriteQueue { | |
public: | |
SingleReadWriteQueue() { | |
tail = head = new Node(0); | |
} | |
void push(int v) { | |
tail = tail->next = new Node(v); | |
} | |
bool pop(int &v) { | |
if (head->next == NULL) { | |
return false; | |
} | |
Node * tmp = head; | |
head = head->next; | |
v = head->val; | |
delete tmp; | |
return true; | |
} | |
private: | |
struct Node { | |
Node(int v) { | |
val = v; | |
next = NULL; | |
} | |
int val; | |
struct Node* next; | |
}; | |
Node *head; | |
Node *tail; | |
}; | |
SingleReadWriteQueue g_q; | |
void push_queue() { | |
long long i = 0; | |
while (1) { | |
g_q.push(i); | |
i = (i + 1) % 1000000; | |
if (rand() % 1000 == 1) { | |
this_thread::sleep_for(std::chrono::milliseconds(rand() % 519)); | |
} | |
} | |
} | |
void pop_queue() { | |
int v; | |
long long i = 0; | |
while (1) { | |
int ret = g_q.pop(v); | |
if (ret == false) { | |
continue; | |
} | |
if (i != v) { | |
cerr << "Error: " << i << " " << v << endl; | |
} | |
i = (i + 1) % 1000000; | |
cout << i << endl; | |
if (rand() % 2009 == 1) { | |
this_thread::sleep_for(std::chrono::milliseconds(rand() % 719)); | |
} | |
} | |
} | |
int main(int argc, char* argv[]) { | |
thread push(push_queue); | |
thread pop(pop_queue); | |
push.join(); | |
pop.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment