-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate-list.cpp
58 lines (46 loc) · 1.05 KB
/
create-list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <pthread.h>
#include <iostream>
#include <unistd.h>
#include <atomic>
#include <memory>
using namespace std;
const int N = 100;
struct Item
{
struct Item *next;
long long value;
};
atomic<Item*> last(nullptr);
Item* liststart = nullptr;
void *thread_func(void *ptr)
{
int self = (int)(size_t)(ptr);
for (int i = 0; i < 1000; ++i) {
auto newitem = new Item();
newitem->value = (self * 1000) + i;
auto old = last.exchange(newitem);
if (!old) {
liststart = newitem;
} else {
old->next = newitem;
}
sched_yield();
}
return NULL;
}
int main()
{
unique_ptr<pthread_t[]> ids(new pthread_t[N]);
for (int i = 0; i < N; ++i) {
pthread_create(&ids[i], NULL, thread_func, (void*) (size_t) i);
}
for (int i = 0; i < N; ++i)
pthread_join(ids[i], NULL);
auto current = liststart;
while (current->next) {
cout << current->value << " ";
current = current->next;
}
cout << current->value;
return 0;
}