c 语言线程小例子

例程:下面通过一个简单例程example.c来展示Linux下的C语言多线程操作。

  /* example.c*/

  #include <stdio.h>

  #include <pthread.h>

  void thread(void)

  {

  int i;

  for(i=0;i<3;i++)

  printf("This is a pthread./n");

  }

  int main(void)

  {

  pthread_t id;

  int i,ret;

  ret=pthread_create(&id,NULL,(void *) thread,NULL);

  if(ret!=0){

  printf ("Create pthread error!/n");

  exit (1);

  }

  for(i=0;i<3;i++)

  printf("This is the main process./n");

  pthread_join(id,NULL);

  return (0);

  }

  编译此程序:gcc example.c -lpthread -o example。

     注意:上面的程序回出现错误的。

    main.cpp:68: error: invalid conversion from ‘void (*)()’ to ‘void* (*)(void*)’
    main.cpp:68: error:   initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)  (void*), void*)’

    需要在最上面添加:typedef void *(*thread_proc)(void *);

   然后:强转ret = pthread_create(&id, NULL, (thread_proc)thread, NULL);

 

  运行example得到如下结果(结果有多样性,根据具体系统的调用算法不同而不同):

  This is the main process.

  This is a pthread.

  This is the main process.

  This is the main process.

  This is a pthread.

  This is a pthread.

  =====================================================================

相关文章
相关标签/搜索