線程同步:
線程的同步需要用到互斥量(mutex)用pthread_mutex_t類型表示。
互斥量(mutex)是一種簡單的加鎖的方法來控制對關心資源的訪問。在同一時間只有一個線程掌握某個互斥上的鎖,擁有鎖的線程可以對共用資源進行訪問。如其它線程希望上鎖一個已經被上了的互斥鎖的資源。則該線程被掛起,知道擁有這把鎖的線程釋放鎖為止。
用到的函數
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t*restrict mutex,
const pthread_mutexattr_t*restrict attr);
pthread_mutex_t mutex =PTHREAD_MUTEX_INITIALIZER;//和調用pthread_mutex_init()函數初始化鎖是一樣的。
功能:初始化鎖
傳回值:成功返回0
參數:
mutex:線程鎖變數的地址
attr:線程鎖變數的屬性,要用預設的屬性初始化鎖就可以把它設為NULL
#include<pthread.h>
intpthread_mutex_destroy(pthread_mutex_t *mutex);
功能:銷毀線程鎖
傳回值:成功返回0
參數:線程鎖的地址
#include<pthread.h>
Int thread_mutex_lock(pthread_mutex_t*mutex);
功能:上鎖(訪問資源),如果互斥量已經上鎖則線程將阻塞上互斥量解鎖
傳回值:成功返回0
#include<pthread.h>
Int thread_mutex_unlock(pthread_mutex_t*mutex);
功能:釋放鎖(釋放資源)
傳回值:成功返回0
參數:線程鎖的地址
#include<pthread.h>
Int thread_mutex_trylock(pthread_mutex_t *mutex);
功能:如果線程不希望阻塞,它就可以用此函數嘗試對互斥量加鎖,如果互斥量未處於加鎖狀態,那麼Int thread_mutex_trylock(pthread_mutex_t*mutex);將鎖住互斥量,不會出現阻塞並返回0.,否則就會失敗,不能鎖住互斥量。
傳回值:成功返回0
參數:線程鎖的地址
例子:
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<pthread.h>
#define FILENAME "testfile"
int fd;
//pthread_mutex_tmutex_lock1,mutex_lock2
pthread_mutex_t mutex_lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_lock2 = PTHREAD_MUTEX_INITIALIZER;
void *pthfun(void *arg)
{
int i=0;
while(i++<5)
{
pthread_mutex_lock(&mutex_lock1);
write(fd,"1",sizeof(char));
pthread_mutex_unlock(&mutex_lock2);
}
pthread_exit(((void *) 0));
// return ((void *) 10);
}
int main()
{
int i=0;
void * ret;
//pthread_mutex_init函數初始化鎖。
//pthread_mutex_init(&mutex_lock1,NULL);
//pthread_mutex_init(&mutex_lock2,NULL);
pthread_ttid;
fd=open(FILENAME,O_RDWR|O_CREAT| O_APPEND | O_TRUNC,0666);
//O_TRUNC 將檔案的長度截為0,(清空檔案)
// O_APPEND 追加到檔案尾 pthread_create(&tid,NULL,pthfun,NULL);
while(i++<5)
{
pthread_mutex_lock(&mutex_lock2);
write(fd,"1",sizeof(char));
pthread_mutex_unlock(&mutex_lock1);
}
pthread_join(tid,&ret);
printf("ret=%d\n", (int)ret);
close(fd);
pthread_mutex_destroy(&mutex_lock1);
pthread_mutex_destroy(&mutex_lock2);
return 0;
}
運行結果為:
看一個例子:
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
pthread_mutex_t mutex_lock1 ,mutex_lock2;
int value=0;
void *pthfun(void *arg)
{
int i=0;
while(i++<5)
{
pthread_mutex_lock(&mutex_lock1);
value+=1;
printf("value+=1\n");
pthread_mutex_unlock(&mutex_lock2);
}
pthread_exit(((void*) 10));
}
int main()
{
int i=0;
void * ret;
pthread_mutex_init(&mutex_lock1,NULL);
pthread_mutex_init(&mutex_lock2,NULL);
pthread_t tid;
pthread_create(&tid,NULL,pthfun,NULL);
while(i++<5)
{
pthread_mutex_lock(&mutex_lock2);
value+=2;
printf("value+=2\n");
pthread_mutex_unlock(&mutex_lock1);
}
pthread_join(tid,&ret);
printf("ret=%d\n",(int)ret);
pthread_mutex_destroy(&mutex_lock1);
pthread_mutex_destroy(&mutex_lock2);
return 0;
}
運行結果: