Linux應用編程和網絡編程(9)------- 線程同步的簡單應用


一,線程的引入

再論進程
1、多進程實現同時讀取鍵盤和鼠標

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main(void)
{
	// 思路就是創建子進程,然後父子進程中分別進行讀鍵盤和鼠標的工作
	int ret = -1;
	int fd = -1;
	char buf[200];
	
	ret = fork();
	if (ret == 0)
	{
		// 子進程
		fd = open("/dev/input/mouse1", O_RDONLY);
		if (fd < 0)
		{
			perror("open:");
			return -1;
		}
		
		while (1)
		{
			memset(buf, 0, sizeof(buf));
			printf("before read.\n");
			read(fd, buf, 50);
			printf("讀出鼠標的內容是:[%s].\n", buf);
		}	
	}
	else if (ret > 0)
	{
		// 父進程
		while (1)
		{
			memset(buf, 0, sizeof(buf));
			printf("before read.\n");
			read(0, buf, 5);
			printf("讀出鍵盤的內容是:[%s].\n", buf);			
		}
	}
	else
	{
		perror("fork:");
	}
	
	return 0;
}

2、使用進程技術的優勢
(1)CPU時分複用,單核心CPU可以實現宏觀上的並行
(2)實現多任務系統需求(多任務的需求是客觀的)

3、進程技術的劣勢
(1)進程間切換開銷大
(2)進程間通信麻煩而且效率低

4、解決方案就是線程技術
(1)線程技術保留了進程技術實現多任務的特性
(2)線程的改進就是在線程間切換和線程間通信上提升了效率。
(3)多線程在多核心CPU上面更有優勢

5、linux中的線程簡介
(1)一種輕量級進程
(2)線程是參與內核調度的最小單元
(3)一個進程中可以有多個線程

7、線程技術的優勢
(1)像進程一樣可被OS調度
(2)同一進程的多個線程之間很容易高效率通信
(3)在多核心CPU(對稱多處理器架構SMP)架構下效率最大化


二,線程常見函數


1、線程創建與回收

  1. pthread_create(); 主線程用來創造子線程的
  2. pthread_join(); 主線程用來等待(阻塞)回收子線程
  3. pthread_detach(); 主線程用來分離子線程,分離後主線程不必再去回收子線程

2、線程取消

  1. pthread_cancel(); 一般都是主線程調用該函數去取消(讓它趕緊死)子線程
  2. pthread_setcancelstate(); 子線程設置自己是否允許被取消
  3. pthread_setcanceltype();

3、線程函數退出相關

  1. pthread_exit();與return退出
  2. pthread_cleanup_push();
  3. pthread_cleanup_pop();

4、獲取線程id
(1)pthread_self();


三,線程同步的簡單使用

分別使用下面三種線程同步的方法實現任務:用戶從終端輸入任意字符然後統計個數顯示,輸入end則結束

1.線程同步之信號量

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


char buf[200] = {0};
sem_t sem;
unsigned int flag = 0;


// 子線程程序,作用是統計buf中的字符個數並打印
void *func(void *arg)
{
	// 子線程首先應該有個循環
	// 循環中阻塞在等待主線程激活的時候,子線程被激活後就去獲取buf中的字符
	// 長度,然後打印;完成後再次被阻塞
	sem_wait(&sem);
	//while (strncmp(buf, "end", 3) != 0)
	while (flag == 0)
	{	
		printf("本次輸入了%d個字符\n", strlen(buf));
		memset(buf, 0, sizeof(buf));
		sem_wait(&sem);
	}
	
	
	pthread_exit(NULL);
}


int main(void)
{
	int ret = -1;
	pthread_t th = -1;
	
	
	
	sem_init(&sem, 0, 0);
	
	ret = pthread_create(&th, NULL, func, NULL);
	if (ret != 0)
	{
		printf("pthread_create error.\n");
		exit(-1);
	}
	
	printf("輸入一個字符串,以回車結束\n");
	while (scanf("%s", buf))
	{
		// 去比較用戶輸入的是不是end,如果是則退出,如果不是則繼續		
		if (!strncmp(buf, "end", 3))
		{
			printf("程序結束\n");
			flag = 1;
			sem_post(&sem);	
			//exit(0);
			break;
		}
		
		// 主線程在收到用戶收入的字符串,並且確認不是end後
		// 就去發信號激活子線程來計數。
		// 子線程被阻塞,主線程可以激活,這就是線程的同步問題。
		// 信號量就可以用來實現這個線程同步
		sem_post(&sem);	
	}

	
	// 回收子線程
	printf("等待回收子線程\n");
	ret = pthread_join(th, NULL);
	if (ret != 0)
	{
		printf("pthread_join error.\n");
		exit(-1);
	}
	printf("子線程回收成功\n");
	
	sem_destroy(&sem);
	
	return 0;
}

編譯的時候加參數 -pthread

2.線程同步之互斥鎖

1、互斥鎖
(1)互斥鎖又叫互斥量(mutex)
(2)相關函數:
pthread_mutex_init ();
pthread_mutex_destroy ();
pthread_mutex_lock();
pthread_mutex_unlock();

(3)互斥鎖和信號量的關係:可以認爲互斥鎖是一種特殊的信號量
(4)互斥鎖主要用來實現關鍵段保護

2、用互斥鎖來實現上節的代碼

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



char buf[200] = {0};
pthread_mutex_t mutex;
unsigned int flag = 0;


// 子線程程序,作用是統計buf中的字符個數並打印
void *func(void *arg)
{
	// 子線程首先應該有個循環
	// 循環中阻塞在等待主線程激活的時候,子線程被激活後就去獲取buf中的字符
	// 長度,然後打印;完成後再次被阻塞
	
	//while (strncmp(buf, "end", 3) != 0)
	sleep(1);
	while (flag == 0)
	{	
		pthread_mutex_lock(&mutex);
		printf("本次輸入了%d個字符\n", strlen(buf));
		memset(buf, 0, sizeof(buf));
		pthread_mutex_unlock(&mutex);
		sleep(1);
	}
	
	
	pthread_exit(NULL);
}


int main(void)
{
	int ret = -1;
	pthread_t th = -1;
	
	
	
	pthread_mutex_init(&mutex, NULL);
	
	ret = pthread_create(&th, NULL, func, NULL);
	if (ret != 0)
	{
		printf("pthread_create error.\n");
		exit(-1);
	}
	
	printf("輸入一個字符串,以回車結束\n");
	while (1)
	{
		pthread_mutex_lock(&mutex);
		scanf("%s", buf);
		pthread_mutex_unlock(&mutex);
		// 去比較用戶輸入的是不是end,如果是則退出,如果不是則繼續		
		if (!strncmp(buf, "end", 3))
		{
			printf("程序結束\n");
			flag = 1;
			
			//exit(0);
			break;
		}
		sleep(1);
		// 主線程在收到用戶收入的字符串,並且確認不是end後
		// 就去發信號激活子線程來計數。
		// 子線程被阻塞,主線程可以激活,這就是線程的同步問題。
		// 信號量就可以用來實現這個線程同步
	}

	
	// 回收子線程
	printf("等待回收子線程\n");
	ret = pthread_join(th, NULL);
	if (ret != 0)
	{
		printf("pthread_join error.\n");
		exit(-1);
	}
	printf("子線程回收成功\n");
	
	pthread_mutex_destroy(&mutex);
	
	return 0;
}

注意:man 3 pthread_mutex_init時提示找不到函數,說明你沒有安裝pthread相關的man手冊。安裝方法:1、虛擬機上網;2、sudo apt-get install manpages-posix-dev

3.線程同步之條件變量

1、相關函數
pthread_cond_init();
pthread_cond_destroy();
pthread_cond_wait ();
pthread_cond_signal/pthread_cond_broadcast();

2、使用條件變量來實現上節代碼

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



char buf[200] = {0};
pthread_mutex_t mutex;
pthread_cond_t cond;
unsigned int flag = 0;


// 子線程程序,作用是統計buf中的字符個數並打印
void *func(void *arg)
{
	// 子線程首先應該有個循環
	// 循環中阻塞在等待主線程激活的時候,子線程被激活後就去獲取buf中的字符
	// 長度,然後打印;完成後再次被阻塞
	
	//while (strncmp(buf, "end", 3) != 0)
	//sleep(1);
	while (flag == 0)
	{	
		pthread_mutex_lock(&mutex);
		pthread_cond_wait(&cond, &mutex);
		printf("本次輸入了%d個字符\n", strlen(buf));
		memset(buf, 0, sizeof(buf));
		pthread_mutex_unlock(&mutex);
		//sleep(1);
	}
	
	
	pthread_exit(NULL);
}


int main(void)
{
	int ret = -1;
	pthread_t th = -1;
	

	pthread_mutex_init(&mutex, NULL);
	pthread_cond_init(&cond, NULL);
	
	ret = pthread_create(&th, NULL, func, NULL);
	if (ret != 0)
	{
		printf("pthread_create error.\n");
		exit(-1);
	}
	
	printf("輸入一個字符串,以回車結束\n");
	while (1)
	{
		//pthread_mutex_lock(&mutex);
		scanf("%s", buf);
		pthread_cond_signal(&cond);
		//pthread_mutex_unlock(&mutex);
		// 去比較用戶輸入的是不是end,如果是則退出,如果不是則繼續		
		if (!strncmp(buf, "end", 3))
		{
			printf("程序結束\n");
			flag = 1;
			
			//exit(0);
			break;
		}
		//sleep(1);
		// 主線程在收到用戶收入的字符串,並且確認不是end後
		// 就去發信號激活子線程來計數。
		// 子線程被阻塞,主線程可以激活,這就是線程的同步問題。
		// 信號量就可以用來實現這個線程同步
	}

	
	// 回收子線程
	printf("等待回收子線程\n");
	ret = pthread_join(th, NULL);
	if (ret != 0)
	{
		printf("pthread_join error.\n");
		exit(-1);
	}
	printf("子線程回收成功\n");
	
	pthread_mutex_destroy(&mutex);
	pthread_cond_destroy(&cond);
	
	return 0;
}

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