美文网首页C和C++常用
Linux pthread 编程

Linux pthread 编程

作者: louyang | 来源:发表于2017-12-19 09:25 被阅读119次

我们知道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

相关文章

  • Linux pthread 编程

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

  • mutex lock 唤醒顺序

    在 Linux 多线程编程中,我们常常用 pthread_mutex_lock 来做线程间同步。当锁被占用时,当前...

  • 互斥锁

    Linux线程-互斥锁pthread_mutex_t

  • iOS多线程--pthread、NSThread

    1 pthread pthread是一套通用的多线程的API,可以在Unix / Linux / Windows ...

  • 多线程pthread_create的参数

    多线程编程 C语言使用pthread_create()函数完成多线程的创建,pthread_create()函数共...

  • iOS多线程

    并发编程推荐文章objc中国的并发编程API挑战 pthread POSIX线程(POSIX threads),简...

  • 多线程(一)

    一、常见的多线程 1、pthread pthread是一套通用的多线程API,适用于Unix\Linux\Wind...

  • python安装pymysql报GCC错

    pip install PyMySQL x86_64-linux-gnu-gcc -pthread -DNDEBU...

  • CMake教程——零碎笔记

    多系统区分 windows下x64和x86区分 将pthread作为默认线程库 由于pthread不是linux的...

  • 多线程编程(pthread)

    简介 pthread - POSIX threads 。POSIX 是IEEE为在各种UNIX操作系统上运行软件,...

网友评论

    本文标题:Linux pthread 编程

    本文链接:https://www.haomeiwen.com/subject/zftbwxtx.html