linux多线程编程小结(一)

线程是进程基本的基本调度单位。而进程是程序执行和资源分配的最小单位。可以减少资源的开销.
线程有专门的线程库来调用Thread.线程的创建用thread_create();

int pthread_create(pthread_t *restrict thread,const pthread_attr_t *restrict attr,
void *(*start_routine)(void*), void *restrict arg);

参数1 :线程的标志
参数2 :线程的属性
参数3 :线程函数
参数4 :线程传递的参数
线程的退出 pthread_exit(void *value_ptr)
等待线程结束
int pthread_join(pthread_t thread, void **value_ptr)
示例程序

#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int global_variable;
void * test1()
{
	 while(1)
	 {
      sleep(2);
      global_variable++;
      printf(" global_variable is %d \r\n",global_variable);
      if(global_variable>5)
      pthread_exit(0);
	}
}
void *test2()
{
	 while(1)
 	{
 	  sleep(3);
      global_variable--;
      printf(" global_variable is %d \r\n",global_variable);
       if(global_variable<0)
      pthread_exit(0);

	}
}
int main(int argc,char *argv[])
{
   pthread_t id1,id2;
   int bit;
   bit=pthread_create(&id1,NULL,test1,NULL);
   if(bit!=0)
   {
   	printf("id1 create error\r\n");
    exit(0);
   }
   bit=pthread_create(&id2,NULL,test2,NULL);
   if(bit!=0)
   {
   	printf("id2 create error\r\n");
   	exit(0);
   }
   pthread_join(id1,NULL);
   pthread_join(id2,NULL);
   return 0;
}

结果如下

 id1global_variable is 1 
 id2global_variable is 0 
 id1global_variable is 1 
 id2global_variable is 0 
 id1global_variable is 1 
 id1global_variable is 2 
 id2global_variable is 1 
 id1global_variable is 2 
 id2global_variable is 1 
 id1global_variable is 2 
 id1global_variable is 3 
 id2global_variable is 2 
 id1global_variable is 3 
 id2global_variable is 2 
 id1global_variable is 3 
 id1global_variable is 4 
 id2global_variable is 3 
 id1global_variable is 4 
 id2global_variable is 3 
 id1global_variable is 4 
 id1global_variable is 5 
 id2global_variable is 4 
 id1global_variable is 5 
 id2global_variable is 4 
 id1global_variable is 5 
 id1global_variable is 6 
 id2global_variable is 5 
 id2global_variable is 4 
 id2global_variable is 3 
 id2global_variable is 2 
 id2global_variable is 1 
 id2global_variable is 0 

小结二

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值