⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 threadtest2.c

📁 基于linux的系统编程程序
💻 C
字号:
/*threadtest2.c*/
#include <stdlib.h>  
#include <stdio.h>  
#include <pthread.h>  
#include <errno.h>   

/*声明线程运行服务程序*/
static void pthread_func_1 (void);   
static void pthread_func_2 (void);   
  
int main (void)   
{   
 /*线程的标识符*/
  pthread_t pt_1 = 0;   
  pthread_t pt_2 = 0;   
  int ret = 0;   
  pthread_attr_t attr = {0};			//属性结构
  
  /*属性设置*/
  pthread_attr_init (&attr); //初始化属性   
  pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM); //绑定
  pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); //分离
	

  /*分别创建线程1、2*/
  ret = pthread_create (&pt_1,			//线程标识符指针
						 &attr,			//默认属性
						(void *)pthread_func_1,//运行函数
						NULL);   		//无参数
  if (ret != 0)   
  {   
     perror ("pthread_1_create");   
  }   
  
  ret = pthread_create (&pt_2, 			//线程标识符指针
						NULL,			//默认属性	
						(void *)pthread_func_2, //运行函数
						NULL);   		//无参数
  if (ret != 0)   
  {   
     perror ("pthread_2_create");   
  }   
  /*等待线程2的结束*/   
  pthread_join (pt_2, NULL);   
  sleep(2);//注意线程2结束时线程1没结束,这里不调用sleep会看不到
  printf ("main programme exit!\n");  
  return 0;   
}   

/*线程1的服务程序*/
static void pthread_func_1 (void)   
{   
  int i = 0;   
     
  for (; i < 6; i++)   
  {   
    printf ("This is pthread1!\n");   
  
    /*i==2时退出,即循环3次*/
    if (i == 2)   
    {   
      pthread_exit (0);   
    }   
  
    sleep (1);   
  }   
}   
/*线程2的服务程序*/ 
static void pthread_func_2 (void)   
{   
  int i = 0;   
  
  for (; i < 3; i++)   
  {   
    printf ("This is pthread2!\n");   
  }   
  
  pthread_exit (0);   
}  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -