linux多线程入门

    linux下的多线程通过pthread实现,下面给个简单的例子。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void* thr_fn()
{
    printf("this is a thread, tid = %d\n", pthread_self());
    printf("thread return\n");
    return (void*)0;
}

int main()
{
    printf("this is the main thread, pid = %d\n", getpid());
    pthread_t tid;
    int ret;
    ret = pthread_create(&tid, NULL, thr_fn, NULL);
    if (ret != 0)
    {
        printf("create thread error\n");
        exit(1);
    }
    pthread_join(tid, NULL);
    printf("main thread return\n");
    return 0;
}

执行输出如下:

 

    主要涉及两个函数:

 int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);      //线程创建函数
  int pthread_join(pthread_t thread, void **retval);                        //等待线程结束函数

 reference:

Linux下的多线程编程

posted @ 2015-08-14 10:30  Sawyer Ford  阅读(164)  评论(0编辑  收藏  举报