pthread_create用法


#include <pthread.h>

int pthread_create(pthread_t *restrict tidp,
const pthread_attr_t *restrict attr,
void *(*start_rtn)(void), 
void *restrict arg);

Returns: 0 if OK, error number on failure

一个参数为指向线程标识符的指针。

第二个参数用来设置线程属性。
第三个参数是线程运行函数的起始地址。
最后一个参数是运行函数的参数。
 
ps:
 

   编译的时候,一定要加上-lpthread选项,不然会报错:undefined reference to `pthread_create'。

  下面来看看pthread_create的声明:

  #include<pthread.h>

  int pthread_create(pthread_t *thread, pthread_addr_t *arr,

           void* (*start_routine)(void *), void *arg);

 

  •  thread   :用于返回创建的线程的ID
  • arr       : 用于指定的被创建的线程的属性,上面的函数中使用NULL,表示使用默认的属性
  • start_routine   : 这是一个函数指针,指向线程被创建后要调用的函数
  • arg      : 用于给线程传递参数,在本例中没有传递参数,所以使用了NULL

 

 

简单的线程程序

 

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
 
#define    NUM_THREADS     8
 
void *PrintHello( void *args)
{
     int thread_arg;
     sleep(1);
     thread_arg = ( int )args;
     printf ( "Hello from thread %d\n" , thread_arg);
     return NULL;
}
 
int main( void )
{
     int rc,t;
     pthread_t thread [NUM_THREADS];
 
     for ( t = 0; t < NUM_THREADS; t++)
     {
         printf ( "Creating thread %d\n" , t);
         rc = pthread_create(& thread [t], NULL, PrintHello, ( void *)t);
         if (rc)
         {
             printf ( "ERROR; return code is %d\n" , rc);
             return EXIT_FAILURE;
         }
     }
     for ( t = 0; t < NUM_THREADS; t++)
         pthread_join( thread [t], NULL);
     return EXIT_SUCCESS;
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM