2 * Written by Josh Dybnis and released to the public domain, as explained at
3 * http://creativecommons.org/licenses/publicdomain
19 #define NUM_ITERATIONS 10000000
20 #define MAX_NUM_THREADS 4
30 static volatile int wait_;
33 void *worker (void *arg) {
34 int id = (int)(size_t)arg;
35 unsigned int r = (unsigned int)(id + 1) * 0x5bd1e995; // seed "random" number generator
36 haz_t *hp0 = haz_get_static(0);
38 // Wait for all the worker threads to be ready.
39 __sync_fetch_and_add(&wait_, -1);
43 for (i = 0; i < NUM_ITERATIONS; ++ i) {
44 r ^= r << 6; r ^= r >> 21; r ^= r << 7; // generate next "random" number
47 node_t *new_head = (node_t *)nbd_malloc(sizeof(node_t));
48 node_t *old_head = stk_->head;
52 new_head->next = temp;
53 } while ((old_head = __sync_val_compare_and_swap(&stk_->head, temp, new_head)) != temp);
57 node_t *head = stk_->head;
63 head = ((volatile lifo_t *)stk_)->head;
66 } while ((head = __sync_val_compare_and_swap(&stk_->head, temp, temp->next)) != temp);
69 haz_defer_free(temp, nbd_free);
77 int main (int argc, char **argv) {
78 //lwt_set_trace_level("m0r0");
84 num_threads = strtol(argv[1], NULL, 10);
86 fprintf(stderr, "%s: Invalid argument for number of threads\n", argv[0]);
89 if (num_threads <= 0) {
90 fprintf(stderr, "%s: Number of threads must be at least 1\n", argv[0]);
95 stk_ = (lifo_t *)nbd_malloc(sizeof(lifo_t));
96 memset(stk_, 0, sizeof(lifo_t));
98 struct timeval tv1, tv2;
99 gettimeofday(&tv1, NULL);
102 pthread_t thread[num_threads];
103 for (int i = 0; i < num_threads; ++i) {
104 int rc = nbd_thread_create(thread + i, i, worker, (void *)(size_t)i);
105 if (rc != 0) { perror("pthread_create"); return rc; }
107 for (int i = 0; i < num_threads; ++i) {
108 pthread_join(thread[i], NULL);
111 gettimeofday(&tv2, NULL);
112 int ms = (int)(1000000*(tv2.tv_sec - tv1.tv_sec) + tv2.tv_usec - tv1.tv_usec) / 1000;
113 printf("Th:%d Time:%dms\n\n", num_threads, ms);