採用posix訊號量實現互斥原語,實現執行緒間同步
/*
* 採用訊號量實現互斥原語
*/#include
#include
#include
#include
#include
#include
#include
#include
#include
#define maxnum 10000
//用乙個結構體封裝命名訊號量
struct slock
;//為訊號量結構體分配記憶體
struct slock* s_alloc()
while((sp->psem == sem_failed) && (errno == eexist));
if(sp->psem == sem_failed)
sem_unlink(sp->name);
return sp;
}//釋放記憶體
void s_free(struct slock* sp)
}//互斥lock
int s_lock(struct slock* sp)
//互斥unlock
int s_unlock(struct slock* sp)
//互斥trylock
int s_trylock(struct slock* sp)
//執行緒函式
static
void* th_fun1(void* parg);
static
void* th_fun2(void* parg);
//封裝結構體作為引數傳給執行緒
struct foo
;int main()
err = pthread_create(&tid2, null, th_fun2, (void*)&obj);
if(err != 0)
//在主線程中等待執行緒退出
pthread_join(tid1, null);
printf("thread 1 exit\n");
pthread_join(tid2, null);
printf("thread 2 exit\n");
s_free(obj.pslock);
exit(0);
}static
void* th_fun1(void* parg)
pobj->count++;
printf("thread 1 print count: %d\n", pobj->count);
s_unlock(pobj->pslock);
}return ((void*)1);
}static
void* th_fun2(void* parg)
pobj->count++;
printf("thread 2 print count: %d\n", pobj->count);
s_unlock(pobj->pslock);
}return ((void*)2);
}
參考:apue第三版第15章 POSIX訊號量和互斥鎖
1 建立訊號量 sem t sem open const char name,int oflag sem t sem open const char name,int oflag,mode t mode,unsigned int value 功能 初始化有名訊號量 int sem init sem ...
systemV訊號量 與 Posix訊號量
一 函式上的區別 訊號量有兩種實現 傳統的system v訊號量和新的posix訊號量。它們所提供的函式很容易被區分 對於所有system v訊號量函式,在它們的名字裡面沒有下劃線。例如,應該是semget 而不是sem get 然而,所有的的posix訊號量函式都有乙個下劃線。下面列出了它們提供的...
訊號量 互斥量
lonelycatcher if only as first.來自 訊號量用在多執行緒多工同步的,乙個執行緒完成了某乙個動作就通過訊號量告訴別的執行緒,別的執行緒再進行某些動作 大家都在semtake的時候,就阻塞在 而互斥鎖是用在多執行緒多工互斥的,乙個執行緒占用了某乙個資源,那麼別的執行緒就無法...