這麽高的懸賞,實例放後面。信號量(sem),如同進程壹樣,線程也可以通過信號量來實現通信,雖然是輕量級的。信號量函數的名字都以"sem_"打頭。線程使用的基本信號量函數有四個。
?信號量初始化。 int?sem_init?(sem_t?*sem?,?int?pshared,?unsigned?int?value);這是對由sem指定的信號量進行初始化,設置好它的***享選項(linux?只支持為0,即表示它是當前進程的局部信號量),然後給它壹個初始值VALUE。
等待信號量。給信號量減1,然後等待直到信號量的值大於0。
int?sem_wait(sem_t?*sem);
釋放信號量。信號量值加1。並通知其他等待線程。
int?sem_post(sem_t?*sem);
銷毀信號量。我們用完信號量後都它進行清理。歸還占有的壹切資源。
int?sem_destroy(sem_t?*sem);#include?<stdlib.h>?
#include?<stdio.h>?
#include?<unistd.h>?
#include?<pthread.h>?
#include?<semaphore.h>?
#include?<errno.h>?
#define?return_if_fail(p)?if((p)?==?0){printf?("[%s]:func?error!/n",?__func__);return;}?
typedef?struct?_PrivInfo?
{?
sem_t?s1;?
sem_t?s2;?
time_t?end_time;?
}PrivInfo;?
static?void?info_init?(PrivInfo*?thiz);?
static?void?info_destroy?(PrivInfo*?thiz);?
static?void*?pthread_func_1?(PrivInfo*?thiz);?
static?void*?pthread_func_2?(PrivInfo*?thiz);?
int?main?(int?argc,?char**?argv)?
{?
pthread_t?pt_1?=?0;?
pthread_t?pt_2?=?0;?
int?ret?=?0;?
PrivInfo*?thiz?=?NULL;?
thiz?=?(PrivInfo*?)malloc?(sizeof?(PrivInfo));?
if?(thiz?==?NULL)?
{?
printf?("[%s]:?Failed?to?malloc?priv./n");?
return?-1;?
}?
info_init?(thiz);?
ret?=?pthread_create?(&pt_1,?NULL,?(void*)pthread_func_1,?thiz);?
if?(ret?!=?0)?
{?
perror?("pthread_1_create:");?
}?
ret?=?pthread_create?(&pt_2,?NULL,?(void*)pthread_func_2,?thiz);?
if?(ret?!=?0)?
{?
perror?("pthread_2_create:");?
}?
pthread_join?(pt_1,?NULL);?
pthread_join?(pt_2,?NULL);?
info_destroy?(thiz);?
return?0;?
}?
static?void?info_init?(PrivInfo*?thiz)?
{?
return_if_fail?(thiz?!=?NULL);?
thiz->end_time?=?time(NULL)?+?10;?
sem_init?(&thiz->s1,?0,?1);?
sem_init?(&thiz->s2,?0,?0);?
return;?
}?
static?void?info_destroy?(PrivInfo*?thiz)?
{?
return_if_fail?(thiz?!=?NULL);?
sem_destroy?(&thiz->s1);?
sem_destroy?(&thiz->s2);?
free?(thiz);?
thiz?=?NULL;?
return;?
}?
static?void*?pthread_func_1?(PrivInfo*?thiz)?
{?
return_if_fail(thiz?!=?NULL);?
while?(time(NULL)?<?thiz->end_time)?
{?
sem_wait?(&thiz->s2);?
printf?("pthread1:?pthread1?get?the?lock./n");?
sem_post?(&thiz->s1);?
printf?("pthread1:?pthread1?unlock/n");?
sleep?(1);?
}?
return;?
}?
static?void*?pthread_func_2?(PrivInfo*?thiz)?
{?
return_if_fail?(thiz?!=?NULL);?
while?(time?(NULL)?<?thiz->end_time)?
{?
sem_wait?(&thiz->s1);?
printf?("pthread2:?pthread2?get?the?unlock./n");?
sem_post?(&thiz->s2);?
printf?("pthread2:?pthread2?unlock./n");?
sleep?(1);?
}?
return;?
}