linux下多线程的使用 pthread_create()

原型:

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

下面是一个多线程的简单例子

/*
XianCheng1.c
*/
#include
#include
#include //调用延时
void *Thread_1(void*arg)
{
    int m,*i=(int*)arg;
    for(m=0;m<*i;m++) 
        {
            printf("线程1 :%d\n",m);
            sleep(1);//延时1秒
        }
}
int main()
{
pthread_t pid1;
int p=5;
    if(pthread_create(&pid1,NULL,Thread_1,&p)) return -1;
       else 
        {
          int n;
          for(n=0;n<7;n++)
          {
           printf("主线程:%d\n",n);
           sleep(1);//延时1秒
                  }
        }
//等待线程结束
    pthread_join(pid1,NULL);  
return 0;
}

多线程编译的时候,不太一样

gcc XianCheng1.c -o XianCheng1 -lpthread

运行

./XianCheng1 

可以看到结果

gcc XianCheng1.c -o XianCheng1 -lpthread
stu@ubuntu:~/zhangbing2/Mycode/XianCheng$ ./XianCheng1 
主线程:0
线程10
主线程:1
线程11
主线程:2
线程12
主线程:3
线程13
主线程:4
线程14
主线程:5
主线程:6

你可能感兴趣的:(linux下c编程)