Linux多线程编程函数

 

创建线程

pthread_create( )如果该函数执行成功,线程就自动开始运行了


pthread_join()函数可以用于将当前线程挂起来等待线程的结束。这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源就被收回。


线程入口函数运行完之后,该线程也就退出了,这也是线程退出一种方法(线程自然“死亡”)。另一种退出线程的方法是使用函数pthread_exit(),这是线程的主动行为.


pthread_cancel()函数实现别的线程中要终止另一个线程的执行




简单实例:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
void *thread1_proc(void *arg)
{
	int i=0;
	while(i<10)
	{
		printf("thread1:%d\n",i);
		fflush(stdout);
		sleep(4);
		i++;
	}
	printf("Thread1 finished!\n");
	pthread_exit(NULL);
}

void *thread2_proc(void *arg)
{
	int i=10;
	while(i<20)
	{
		printf("                  thread2:%d\n",i);
		fflush(stdout);
		sleep(2);
		i++;
	}
	printf("Thread2 finished!\n");
	pthread_exit(NULL);

}

int main()
{
	pthread_t thread1,thread2;
	if(pthread_create(&thread1,NULL,thread1_proc,NULL)!=0)	
		perror("Create thread1 failed");
	if(pthread_create(&thread2,NULL,thread2_proc,NULL)!=0)
		perror("Create thread2 failed");
	
	pthread_join(thread1,NULL);
	pthread_join(thread2,NULL);
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值