简单线程实验

/*
名称:简单线程实验
说明:线程是轻量级的进程。我们可以通过创建线程来达到较小的开销(比线程来说)。
线程的使用主要几个API函数,在此简单介绍几个:

(1).

函数定义int  pthread_create((pthread_t  *thread,  pthread_attr_t  *attr,  void (*start_routine)(void  *),  void  *arg)

    功能:创建线程(实际上就是确定调用该线程函数的入口点),在线程创建以后,就开始运行相关的线程函数。
参数:
      thread:线程标识符;
      attr:线程属性设置;
      start_routine:线程函数的起始地址;
      arg:传递给start_routine的参数;
      返回值:成功,返回0;出错,返回-1。

(2).

函数定义: int pthread_join(pthread_t thread, void **retval);
功能 :pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待

线程的资源被收回。如果线程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
代码中如果没有pthread_join主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行
就结束了。加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会
执行。
参数 :
thread: 线程标识符,即线程ID,标识唯一线程。
retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号

*/

#include 
#include 
#include 
#include 


void thread(void)
{
    int i;
    for(i = 0;i<50;++i)
    {
        printf("this is a pthread.\n");
    }
}


int main(void)
{
   pthread_t id;    //声明线程id号
   int i,ret;   
   ret = pthread_create(&id,NULL,(void*)thread,NULL);   //创造线程函数

     if(ret != 0)
   {
        printf("Create pthread error!\n");
        exit(0);
   }

     for(i = 0;i<50;++i)
     {
         printf("This is a main process.\n");
     }

     pthread_join(id,NULL);     //线程同步函数(子线程等待此函数返回后,才能释放其资源)

     return 0;

}

你可能感兴趣的:(操作系统)