1. 程式人生 > >執行緒實驗(一)

執行緒實驗(一)

程式設計實現以下功能:
主執行緒實現以下功能:
    定義全域性變數key;
    建立兩個執行緒;
    如果執行緒正常結束,得到執行緒的結束狀態值,並列印;
執行緒一完成以下操作:
    設定全域性變數key的值為字串“hello world”;
    列印字串“當前執行緒ID:key值”;
    接收到執行緒二傳送的取消請求訊號後退出;
    結束的時候列印字串“thread1 ,exited!:key值”;
執行緒二完成以下操作:
    設定key值為6;
    給執行緒一發送取消請求訊號;
    結束的時候列印字串“thread2,exited!:key值”;

 

執行緒是在一個程式內部能被作業系統排程並併發執行的任務。

執行緒有自己的執行線索,能夠完成指定任務;

執行緒自己一般不擁有系統資源,只擁有少量在執行中必不可少的資源(程式計數器,一組暫存器,棧,執行緒訊號掩碼,區域性執行緒變數和執行緒私有資料);

與同屬於一個程序的其它執行緒共享程序擁有的所有資源;

可以相互協作完成程序所要完成的任務。

執行緒優點如下:

1.節儉。2.程序間方便的訊號通訊方式。

在此次實驗中需要用到的知識點包括:執行緒取消函式和執行緒清理函式以及執行緒私有資料相關知識。

整個實驗流程主要為:

1.主函式建立兩個執行緒,在兩個執行緒中,分別註冊執行緒清理函式pthread_cleanup()函式,在函式中列印題目要求的字串;

2.線上程1中,列印題目要求的字串;

3.線上程2中利用pthread_cancle函式向執行緒1傳送執行緒取消函式;

4.建立執行緒私有資料key,在兩個執行緒中分別為他們賦值為:“hello world”和“6”。

程式如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <pthread.h>
pthread_key_t key;

void cleanup(void *arg)
{
	printf("%s\n",(char *)arg);
}

void *child_thread1(void *arg)
{
	char *str = "Hello World";
	printf("The child_thread1 run!\n");
	printf("The thread id is: %d\n",syscall(SYS_gettid));
	if(pthread_setspecific(key,str) < 0)
	  perror("pthread_setspecific");

	char *get_key = (char *)pthread_getspecific(key);
	printf("The thread1's key is: %s\n",get_key);

	pthread_cleanup_push(cleanup,"Thread1,exited!");
	pthread_cleanup_pop(1);
}

void *child_thread2(void *arg)
{
	int num = 6;
	printf("The child_thread2 run!\n");

	if(pthread_cancel((pthread_t)arg) < 0)
	  perror("pthread_cancle");

	if(pthread_setspecific(key,(void *)num) < 0)
	  perror("pthread_setspecific");
	int *get_key = (int *)pthread_getspecific(key);

	printf("The thread2's key is: %d\n",get_key);
	pthread_cleanup_push(cleanup,"Thread2,exited!");
    pthread_cleanup_pop(1);
}

void *thread(void *arg)
{
	pthread_t tid1,tid2;
	void *tret1,*tret2;

	printf("This is the main pthread!\n");

	if(pthread_key_create(&key,NULL) < 0)
	  perror("phtread_key_create");
	if(pthread_create(&tid1,NULL,(void *)child_thread1,NULL) < 0)
	  perror("pthread_create");
	
	pthread_join(tid1,&tret1);
	printf("The pthread1 exited is: %d\n",(long)tret1);

	if(pthread_create(&tid2,NULL,(void *)child_thread2,&tid1) < 0)
	  perror("pthread_create");

	pthread_join(tid2,&tret2);
	printf("The pthread2 exited is: %d\n",(long)tret2);
}

int main()
{
	pthread_t id;
	if(pthread_create(&id,NULL,(void *)thread,NULL) < 0)
	  perror("pthread_create");

	sleep(1);
	return 0;
}

程式編譯會報型別轉換的警告,不影響執行結果!

程式執行結果如下: