线程实验(一)

编程实现以下功能:
主线程实现以下功能:
    定义全局变量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;
}

程序编译会报类型转换的警告,不影响运行结果!

程序运行结果如下:

猜你喜欢

转载自blog.csdn.net/Wangguang_/article/details/85058013