Linux線程互斥鎖

線程互斥鎖的設置就是爲了多線程之間臨界資源更好的共享,加了鎖的資源就不能被其他的線程訪問,除非

等到佔用鎖的線程釋放該鎖。

互斥鎖的操作主要包括互斥鎖初始化、上鎖、判斷上鎖、解鎖、摧毀互斥鎖。分別由以下幾個函數實現

#include <pthread.h>

int pthread_mutex_init (pthread_mutex_t* mutex, const pthread_mutexattr_t* mutexattr);

int pthread_mutex_lock(pthread_mutex_t* mutex);

int pthread_mutex_trylock(pthread_mutex_t *mutex);

int pthread_mutex_unlock (pthread_mutex_t* mutex);

int pthread_mutex_destroy (pthread_mutex_t* mutex);

下面是一段代碼

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>

void *function(void *arg);
pthread_mutex_t mutex;
int counter = 0;

int main(int argc, char *argv[])
{
	int rc1,rc2;
	char *str1="abcdefg";
	char *str2="123456";
	pthread_t thread1,thread2;

	pthread_mutex_init(&mutex,NULL);
	if((rc1 = pthread_create(&thread1,NULL,function,str1)))
	{
		fprintf(stdout,"thread 1 create failed: %d\n",rc1);
	}

	if(rc2=pthread_create(&thread2,NULL,function,str2))
	{
		fprintf(stdout,"thread 2 create failed: %d\n",rc2);
	}

	pthread_join(thread1,NULL);
	pthread_join(thread2,NULL);
	return 0;
}

void *function(void *arg)
{
	char *m;
	m = (char *)arg;
	pthread_mutex_lock(&mutex);
	while(*m != '\0')
	{
		printf("%c",*m);
		m++;
		fflush(stdout);
		sleep(1);
	}
	printf("\n");
	pthread_mutex_unlock(&mutex);
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章