If your compiler supports the C11 standard, in particular stdatomic.h
, you can do this.
The following is a rough example that should give you the basic idea. It is not very difficult. This one uses posix streams, but you should be able to use any stream library.
#include <stdio.h> #include <stdatomic.h> #include <pthread.h> #define ELEMENTS_N 500000 _Atomic unsigned int x; unsigned int N; unsigned int anyArray[ELEMENTS_N]; void * ThreadLoop ( void * args) { unsigned int l; while( (l = atomic_load( &x )) < N ) { if ( atomic_compare_exchange_weak( &x, &l, l + 1 ) ) { anyArray[l] = l; } } return 0; } int main (int argc, char *argv[] ) { pthread_t th1; pthread_t th2; int v; atomic_store( &x, 0 ); N = ELEMENTS_N; v = pthread_create(&th1, NULL, &ThreadLoop, NULL ); v = pthread_create(&th2, NULL, &ThreadLoop, NULL ); pthread_join( th1, NULL ); pthread_join( th2, NULL ); for(v = 0; v < ELEMENTS_N; v++ ) { printf("%d ", anyArray[v] ); } return 0; }
user2074102
source share