初探线程——pthread_create

  上一篇博客演示了一个最简单的进程的创建过程,这篇博客来演示一个最基础的线程的例子。corecible回复我上篇博文时说:“不过真正的项目开发中,开子进 程用的很少。大多都是线程。”其实也说得挺有道理的,因为像java这样的语言中,原生就支持线程,并提供了一套完整的通信的方案。在linux中,线程实际上就是一个轻量级的进程,因为他们都是通过调用do_fork()函数,传入不同的参数实现的。本来想先写篇关于fork()实现分析的文章,后来考虑到线程和进程在linxu实现中的相同点,所以就先写这篇博文了。

  首先看个最基础的线程的实现:

 1 #include<stdio.h>
 2 #include<pthread.h>
 3 
 4 
 5 void *print_thread_id(void *arg)
 6 {
 7         /* 打印当前线程的线程号*/
 8         printf("Current thread id is %u\n", (unsigned)pthread_self());
 9 }
10 
11 int main(int argc, char *argv[])
12 {
13         pthread_t thread;               /*保存线程号*/
14 
15         /*创建一个线程  */
16         pthread_create(&thread, NULL, print_thread_id, NULL);
17 
18         sleep(1);                         /*休眠1s*/
19 
20         /*打印进程号    */
21         printf("Main thread id is %u\n", (unsigned)pthread_self());
22 
23         return 0;
24 }
25 


   编译的时候,一定要加上-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

 

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

posted @ 2010-05-19 21:46  MR_H  阅读(23623)  评论(13编辑  收藏  举报