Linux系统编程——线程函数(三)

今天我们编写一个程序来实现线程有关的函数:

主要使用了平pthread_testcancelhan函数和pthread_cancel函数,

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

void *tfn(void *arg)
{
	int i;

	i = (int)arg; //强转。

	if (i == 2)
    {
        pthread_testcancel();	//自己添加取消点*/
        pthread_cancel(pthread_self());
    }
		
	sleep(i);	 //通过i来区别每个线程

	printf("I'm %dth thread, Thread_ID = %lu\n", i+1, pthread_self());

	return NULL;
}

int main(int argc, char *argv[])
{
	int n = 5, i;
	pthread_t tid;

	for (i = 0; i < n; i++) {
		pthread_create(&tid, NULL, tfn, (void *)i);
		//将i转换为指针,在tfn中再强转回整形。
	}

	sleep(n);
	printf("I am main, I'm a thread!\n" 
			"main_thread_ID = %lu\n", pthread_self());//获取线程id

	return 0;
}

程序运行结果:

I'm 1th thread, Thread_ID = 3086220176
I'm 2th thread, Thread_ID = 3075730320
I'm 4th thread, Thread_ID = 3054750608
I'm 5th thread, Thread_ID = 3044260752
I am main, I'm a thread!
main_thread_ID = 3086223040



函数综合使用实例:

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


void *tfn1(void *arg)
{
	printf("thread 1 returning\n");

	return (void *)111; 
}

void *tfn2(void *arg)
{
	printf("thread 2 exiting\n");
	pthread_exit((void *)222);
}

void *tfn3(void *arg)
{
	while (1) {
		//printf("thread 3: I'm going to die in 3 seconds ...\n");
		//sleep(1);

		pthread_testcancel();	//自己添加取消点*/
	}

    return (void *)666;
}

int main(void)
{
	pthread_t tid;
	void *tret = NULL;

	pthread_create(&tid, NULL, tfn1, NULL);
	pthread_join(tid, &tret);
	printf("thread 1 exit code = %d\n\n", (int)tret);

	pthread_create(&tid, NULL, tfn2, NULL);
	pthread_join(tid, &tret);
	printf("thread 2 exit code = %d\n\n", (int)tret);

	pthread_create(&tid, NULL, tfn3, NULL);
	sleep(3);
    pthread_cancel(tid);
	pthread_join(tid, &tret);
	printf("thread 3 exit code = %d\n", (int)tret);

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值