- 论坛徽章:
- 0
|
flw程序改动版。TEST1, TEST2可以选择。
可以看到原子性。
- # include <stdio.h>
- # include <stdlib.h>
- # include <pthread.h>
- # include <unistd.h>
- int runFlag = 1;
- int count = 0;
- #define TEST2
- void *incCount( int id );
- int main( void )
- {
- pthread_t thread;
- int i;
- int ret;
- for( i=0; i<6; i++ ){
- ret = pthread_create( &thread, NULL, (void *(*)(void *))incCount, (void *)i );
- if ( ret != 0 ){
- perror( "pthread_create" );
- exit(-1);
- }
- }
- printf( "Wait 5 seconds...\n" );
- sleep(5);
- printf( "Modify runFlag, stop all work thread.\n" );
- runFlag = 0;
- sleep(1);
- printf( "count = [%d]\n", count );
- printf( "Done.\n" );
- return 0;
- }
- void *incCount( int id )
- {
- int i;
- unsigned int k, v;
- id++;
- k = 0x11111111*id;
- printf( "Hello, I am pthread %d\n", id );
- while(runFlag){
- for( i=0; i<10000; i++ ){
- count = k;
- #ifdef TEST1
- v = count;
- if((v & 0x0000ffff) != (v >> 16)) {
- printf("%p %p\n", v, count);
- }
- #endif
- #ifdef TEST2
- if(count != k)
- printf("%p %p\n", k, count);
- #endif
- }
- }
- printf( "[%d] Done.\n", id );
- return NULL;
- }
复制代码 |
|