Linux c 开发-9 一个简单的多线程C程序

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void message( void *ptr ); 
char *message1 = "thread1";
int main()
{
  pthread_t thread1;
  int ret_thrd1;
  void *retval;
  ret_thrd1 = pthread_create(&thread1, NULL, (void *)&message, (void *) message1);
  int tmp1 = pthread_join(thread1, &retval);
  printf("thread start");
  sleep(2);
}
void message( void *ptr ) 
{
  int i = 0;
  for(i=0;i<5;i++)
  {
	printf("%d,%s\n",i,(char*)ptr);
  }
}

  

如上是一个简单的多线程程序,新建一个Makefile文件

test.o:test.c
	gcc test.c -o test.o -lpthread

如果在linux下编译需要加-lpthread,windows下可以不加,另外linux下printf后面要加\n才能及时显示结果。pthread_join相当于Windows C++中的WaitForSingleObject。

编译运行,结果如下

 

posted @ 2021-03-27 23:33  zhaogaojian  阅读(75)  评论(0编辑  收藏  举报