Skip to content

Instantly share code, notes, and snippets.

@dchiji
Created October 26, 2009 16:47
Show Gist options
  • Save dchiji/218792 to your computer and use it in GitHub Desktop.
Save dchiji/218792 to your computer and use it in GitHub Desktop.
#include <pthread.h>
#include <stdio.h>
#include <time.h>
void *func(void *param_p)
{
int *p = (int *)param_p;
printf("## start: %u\n", (unsigned int)pthread_self());
for(int i = 0; i < 100000; i++) {
while(!__sync_bool_compare_and_swap(p, *p, *p + 1));
printf("%u\n", *p);
}
pthread_exit(NULL);
}
int main()
{
int *p = new int;
pthread_t *tid = new pthread_t[300];
*p = 0;
for(int i = 0; i < 300; i++) {
if(pthread_create(tid + i, NULL, func, (void *)p) != 0) {
perror("pthread_create(3)");
}
}
for(int i = 0; i < 300; i++) {
pthread_join(tid[i], NULL);
}
printf("*p=%u\n", *p);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment