Linux pthread 编程

我们知道Linux操作系统中,不同的进程是并行运行的。每个进程都拥有自己独立的虚拟内存空间,好像整个系统都由自己独占的一样。

一个进程内部,还可以拥有多个并行运行的代码片断,被称之为线程(thread)。线程隶属于进程,父子关系。同一进程内部的线程共享同一虚拟内存空间,所以启动或终止一个线程,比启动和终止一个进程要快,而且需要的系统资源少。我们称之为轻量级的并行解决方案。

线程的编程方法是,定义一个函数和其参数,然后用 pthread_create() 启动一个线程并执行这个函数。

#include <stdio.h>   //printf
#include <unistd.h>  //sleep
#include <pthread.h> //pthread_xxx

void *thread_func(void *p)
{
    long i = (long)p;

    for (int j = 0; j < 5; j++)
    {
        printf("--- %d\n", i);
    }

    return NULL;
}

int main()
{
    pthread_t t1, t2;
    pthread_create(&t1, 0, thread_func, (void *)1);
    pthread_create(&t2, 0, thread_func, (void *)2);

    sleep(3);

    return 0;
}
# gcc pthread-create.c -lpthread -o pthread-create && ./pthread-create
--- 2
--- 2
--- 2
--- 2
--- 2
--- 1
--- 1
--- 1
--- 1
--- 1
线程间同步

在主线程中使用 pthread_join() 来等待其他线程结束。

# cat pthread-sync.c

#include <stdio.h>   //printf
#include <pthread.h> //pthread_xxx

void *thread_func(void *p)
{
    long i = (long)p;

    for (int j = 0; j < 5; j++)
    {
        printf("--- %d\n", i);
    }

    return NULL;
}

int main()
{
    pthread_t t1, t2;
    pthread_create(&t1, 0, thread_func, (void *)1);
    pthread_create(&t2, 0, thread_func, (void *)2);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    return 0;
}
# gcc pthread-create.c -lpthread -o pthread-create && ./pthread-create
--- 2
--- 2
--- 2
--- 2
--- 2
--- 1
--- 1
--- 1
--- 1
--- 1
参考

http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容