thread

来源:互联网 发布:u盘centos 7安装教程 编辑:程序博客网 时间:2024/06/07 16:05

thread1.c

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

char message[]="hello";

void* th_fun(void *arg)
{
  printf("the thread is runing,the arg is %s\n",(char*)arg);
  sleep(3);
  strcpy(message,"bye");
  pthread_exit("thank you");
}

int main()
{
  int res;
  pthread_t thread;
  void* th_return;
 
  res = pthread_create(&thread, NULL, th_fun, (void*)message);
  if(0 != res)
  {
    perror("the thread create failure");
    exit(EXIT_FAILURE);
  }

  printf("waiting..\n");
  res = pthread_join(thread, &th_return);
  if(0 != res)
  {
     printf("the thread join failure\n");
     exit(EXIT_FAILURE);
  }
 
  printf("thread join,it returned %s\n",(char*)th_return);
  printf("message now is %s\n",message);
  exit(EXIT_SUCCESS);
}

 

 

thread2.c

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

int run_now = 1;

void* th_fun(void *arg)
{
  int cout=0;
  while(cout++<20)
  {
      if(2==run_now)
      { 
 printf("2\n");
 run_now = 1;
      }
      else
      {
 sleep(1);
      }
  }
}

int main()
{
  int res;
  pthread_t thread;
 
  res = pthread_create(&thread, NULL, th_fun, NULL);
  int cout1=0;
  while(cout1++<20)
  {
      if(1==run_now)
      { 
 printf("1\n");
 run_now = 2;
      }
      else
      {
 sleep(2);
      }
  }

  exit(EXIT_SUCCESS);
}

 

 

 

 

 

原创粉丝点击