多線程編程

線程

  • 創建線程pthread_create
 /* Create a new thread, starting with execution of START-ROUTINE
    getting passed ARG.  Creation attributed come from ATTR.  The new
    handle is stored in *NEWTHREAD.  */
extern int pthread_create (pthread_t *__restrict __newthread,
               const pthread_attr_t *__restrict __attr,
               void *(*__start_routine) (void *),
               void *__restrict __arg) __THROWNL __nonnull ((1, 3));

創建線程成功後返回0,否則創建失敗。通常這樣使用:

pthread_create(&thread, NULL, (void *)&func, (void *)args); func是進程或者線程對應執行的函數,args是func的入參。
  • 結束線程pthread_exit
/* Terminate calling thread.
   The registered cleanup handlers are called via exception handling
   so we cannot mark this function with __THROW.
*/
extern void pthread_exit (void *__retval) __attribute__ ((__noreturn__));
  • 線程等待pthread_join
 /* Make calling thread wait for termination of the thread TH.  The
    exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN
    is not NULL.
 
    This function is a cancellation point and therefore not marked with
    __THROW.
*/
 extern int pthread_join(pthread_t __th, void **__thread_return);

pthread_create調用成功以後,新線程和老線程誰先執行是不確定的,取決與操作系統對線程的調度。如果需要等待指定的線程結束,需要使用pthread_join函數,它類似與多進程編程中的waitpid函數。執行成功時返回0,且thread_return非空。

  • 舉栗子:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void print_message_function(void *ptr);

int main()
{
	int tmp1,tmp2;
	void *retval;
	pthread_t thread1, thread2;
	char *message1 = "thread1:hello world!";
	char *message2 = "thread2:hello world!";

	int ret_thrd1, ret_thrd2;

	ret_thrd1 = pthread_create(&thread1, NULL, (void*)&print_message_function, (void*)message1);
	if (ret_thrd1 != 0){
		printf("create thread1 fail.\n");
	}else{
		printf("create thread1 success.\n");
	}

	ret_thrd2 = pthread_create(&thread2, NULL, (void*)&print_message_function, (void*)message2);
	if (ret_thrd2 !=0){
		printf("create thread2 fail.\n");
	}else{
		printf("create thread2 success.\n");
	}
	
	tmp1 = pthread_join(thread1, &retval);
	printf("thread1 return value is %d\n", (int)retval);
	printf("thread1 return value is %d\n", tmp1);
	if (0 != tmp1){
		printf("cannot join with thread1.\n");
	}
	printf("thread1 end\n");

	tmp2 = pthread_join(thread2, &retval);
	printf("thread2 return value is %d\n", (int)retval);
	printf("thread2 return value is %d\n", tmp2);
	if (0 != tmp2){
		printf("cannot join with thread2.\n");
	}
	printf("thread2 end\n");

    return 0;
}

void print_message_function(void *ptr){
	int i;
	for (i=0;i<5;i++)
		printf("%s:%d\n", (char*)ptr, i);

}

編譯:gcc -o test thread_hello_world.c -lpthread

兩次執行./test的結果如下。分析一下第1次執行的結果。main函數是一個父進程,父進程嘗試創建2個子進程(線程)。在執行pthread_create創建線程thread1之前,進程在main函數中執行,當執行到pthread_create時,這時候已經有2個進程(在linux環境中,線程也稱之爲輕量級進程),分別是father,thread1。從第1次結果中可以看到,father創建thread1成功後,執行了thread1,但是thread1還沒有執行結束前又回到了father進程中,father進程成功創建了thread2,這個時候已經又3個進程了:father,thread1,thread2。操作系統這個時候調度了thread2執行,但是thread2只執行了”thread2:hello world!:0"後立即切換到了thread1,把thread1中剩餘沒有打印完的次數執行完成。接着切換到thread2進程。等到thread1和thread2執行結束後,fahter執行到最後退出。

//第1次
$ ./test 
create thread1 success.
thread1:hello world!:0
thread1:hello world!:1
thread1:hello world!:2
thread1:hello world!:3
create thread2 success.
thread2:hello world!:0
thread1:hello world!:4
thread1 return value is 23
thread1 return value is 0
thread1 end
thread2:hello world!:1
thread2:hello world!:2
thread2:hello world!:3
thread2:hello world!:4
thread2 return value is 23
thread2 return value is 0
thread2 end
//第2次
$ ./test 
create thread1 success.
thread1:hello world!:0
thread2:hello world!:0
thread2:hello world!:1
thread2:hello world!:2
thread2:hello world!:3
thread2:hello world!:4
create thread2 success.
thread1:hello world!:1
thread1:hello world!:2
thread1:hello world!:3
thread1:hello world!:4
thread1 return value is 23
thread1 return value is 0
thread1 end
thread2 return value is 23
thread2 return value is 0
thread2 end

多線程的同步與互斥----鎖

  • 定義一個鎖
//mutex
pthread_mutex_t mutex;
  • 使用鎖之前初始化
//在主線程中初始化鎖爲解鎖狀態
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
//在編譯時初始化鎖爲解鎖狀態
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  • 加鎖
/* Lock a mutex.  */
extern int pthread_mutex_lock (pthread_mutex_t *__mutex);

加鎖成功時返回0,否則加鎖失敗。

  • 釋放鎖
/* Unlock a mutex.  */
extern int pthread_mutex_unlock (pthread_mutex_t *__mutex);

開鎖成功時返回0,否則釋放鎖失敗。

  • 舉栗子
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int sharedi = 0;

void increse_num(void);

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main()
{
	int ret;
	pthread_t thrd1, thrd2, thrd3;

	ret = pthread_create(&thrd1, NULL, (void*)increse_num, NULL);
	ret = pthread_create(&thrd2, NULL, (void*)increse_num, NULL);
	ret = pthread_create(&thrd3, NULL, (void*)increse_num, NULL);

	pthread_join(thrd1, NULL);
	pthread_join(thrd2, NULL);
	pthread_join(thrd3, NULL);

	printf("sharedi = %d\n", sharedi);
	return 0;
}

void increse_num(void)
{
	long i, tmp;
	for (i=0; i<100000;i++){
		/* get the lock */
		if (pthread_mutex_lock(&mutex) != 0){
			perror("pthread_mutex_lock.");
			exit(EXIT_FAILURE);
		}

		tmp = sharedi;
		tmp++;
		sharedi = tmp;

		/* release the lock. */
		if (pthread_mutex_unlock(&mutex) != 0){
			perror("pthread_mutex_unlock.");
			exit(EXIT_FAILURE);
		}
	}

	return;
}

如果不在 increse_num函數中增加sharedi的操作前加鎖,那麼sharedi每次執行後的結果是隨機的。加鎖之後,可以保證每次結果都是確定的。

多線程的同步與互斥----信號量

信號量本質上是一個非負數的整數計數器,被用來控制對公共資源的訪問。當訪問公共資源的時候,調用信號量增加函數sem_post()對其進行加1,當退出訪問公共資源的時候,調用函數sem_wait()來減少信號量。

  • 定義一個信號量、使用前需要初始化
#include <semaphore.h>
//定義
sem_t sem;
//調用初始化函數
int sem_init(sem_t *sem, int pshared, unsigned int value);
  • 信號量操作
#include <semaphore.h>

//信號量加1操作
int sem_wait(sem_t *sem);

//信號量減1操作,如果信號量已經是0,那麼執行sem_post時,該操作被阻塞
int sem_post(sem_t *sem);

//不再使用該信號量時,刪除它
int sem_destroy(sem_t *sem);

以上操作執行成功時返回0,否則執行失敗。

  • 舉栗子
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

#define MAXSIZE 16

int stack[MAXSIZE];
int size = 0;

sem_t sem;

//creater
void provide_data(void){
	int i;
	for (i=0; i<MAXSIZE; i++){
		stack[i] = i;
		sem_post(&sem);
	}
}

//consumer
void handle_data(void){
	int i;
	while((i = size++) < MAXSIZE){

//如果消費者的消費速度比生產者的速度快,此處會阻塞消費者;直到有值(stack[MAXSIZE])可被消費時才
//不阻塞
		sem_wait(&sem);
		printf("multiply: %d x %d = %d\n", stack[i], stack[i], stack[i]*stack[i]);
		sleep(1);
	}
}

int main(void)
{
	pthread_t provider, handler;

	sem_init(&sem, 0, 0);
	pthread_create(&handler, NULL, (void*)handle_data, NULL);
	pthread_create(&provider, NULL, (void*)provide_data, NULL);
	pthread_join(provider, NULL);
	pthread_join(handler, NULL);

	sem_destroy(&sem);

	return 0;
}

這是一個非常樸素的生產者-消費者問題,使用了信號量來保證消費者不會提前去消費生產者沒有生產的值。

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