pthead_create的使用,英语不会是硬伤

英语不会果然是硬伤啊,英文的看了半天,就是一点都看不懂啊,下面来用中文解释下这个函数把,汗

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> 1 #include<stdio.h>
 #include<pthread.h>
 
 
 void *print_thread_id(void *arg)
 {
         /* 打印当前线程的线程号*/
         printf("Current thread id is %u\n", (unsigned)pthread_self());
 }
 
 int main(int argc, char *argv[])
 {
         pthread_t thread;               /*保存线程号*/
 
         /*创建一个线程  */
         pthread_create(&thread, NULL, print_thread_id, NULL);
 
         sleep(1);                         /*休眠1s*/
 
         /*打印进程号    */
         printf("Main thread id is %u\n", (unsigned)pthread_self());
 
         return 0;
 }

  

编译的时候,一定要加上-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, 这个参数传递给start_routine();

   线程相对进程来说,有几大优点,一是其切换速度快,其保存现场花费的时间比进程少得多,二是:线程间的同步比进程简单(至少我是这样认为的)。当然,可能还有很多其他的优点我没有发现,还请您多多指教。

转自:http://www.cnblogs.com/huangwei/archive/2010/05/19/1739593.html

原文地址:https://www.cnblogs.com/cdwodm/p/2694271.html