多线程编程,线程同步,线程互斥示例
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> int count,v1,v2; int flags = 1; sem_t sem; pthread_mutex_t mt; void *fun(void *arg) { int ret = -1; while(1) { #if 0 ret = sem_wait(&sem); if ( -1 == ret ) { perror("sem_init"); return ; } #else ret = pthread_mutex_lock(&mt); if (0 != ret) { perror("pthread_mutex_lock"); return -1; } #endif if ( v1 != v2 ) printf("******* %d,%d\n",v1,v2); #if 0 ret = sem_post(&sem); if ( -1 == ret ) { perror("sem_init"); return ; } #else ret = pthread_mutex_unlock(&mt); if (0 != ret) { perror("pthread_mutex_lock"); return -1; } #endif } *((int *)arg) = 3; pthread_exit("fun");//exit } int main(int argc,char **argv) { int a = 0; pthread_t id; int ret = -1; void * val = NULL; #if 0 ret = sem_init(&sem,0,1); if ( -1 == ret ) { perror("sem_init"); return -1; } #else ret = pthread_mutex_init(&mt,NULL); if( 0 != ret) { perror("pthread_mutex_init"); return -1; } #endif ret = pthread_create(&id,NULL,fun,(void*)&a);//fork if ( 0 != ret ) { perror("pthread_creat"); return -1; } while(1) { #if 0 ret = sem_wait(&sem); if ( -1 == ret ) { perror("sem_init"); return -1; } #else ret = pthread_mutex_lock(&mt); if (0 != ret) { perror("pthread_mutex_lock"); return -1; } #endif count++; v1=count; v2=count; #if 0 ret = sem_post(&sem); if ( -1 == ret ) { perror("sem_init"); return -1; } #else ret = pthread_mutex_unlock(&mt); if (0 != ret) { perror("pthread_mutex_lock"); return -1; } #endif } ret = pthread_join(id,&val);//wait if ( 0 != ret ) { perror("pthread_join"); return -1; } printf("return val is %s\n",val); printf("%d**\n",a); return 0; }