[C 语言笔记--Day08] Thread

大纲

  1. 什麽是 thread ?
  2. Thread Creation
  3. Thread Termination
  4. Thread IDs
  5. Joining
  6. Detaching a thread
  7. 程序码范例
  8. 参考资料

1. 什麽是 thread ?

一个 process 使用多个 thread 是一种让程序平行处理的方式,
跟使用 multi processes 来实作平行程序的区别在於
multi threads 是共用同一个 virtual memory
这使得 thread 跟 thread 之间的传递资料比较容易(process 还要建立 pipe)
但相对的也比较危险

2. Thread Creation

#include <pthread.h>

int pthreaqd_create(pthread_t *thread, const pthread_attr_t *attr,
                    void *(*start)(void *), void *arg);
            // Returns 0 on sucess, or a positive error number on error
  • thread :用来区别各个 thread 用,ID 的功能
  • attr :attribute
  • start :这个新的 thread 要执行的 function
  • arg :塞进 start 这个 function 的参数

3. Thread Termination

#include <pthread.h>

void pthread_exit(void *retval);

4. Thread IDs

取得自己的 thread ID

#include <pthread.h>

pthread_t pthread_self(void);
            // Returns the thread ID of the calling thread

看看是不是同一个 thread

#include <pthread.h>

int pthread_equal(pthread_t t1, pthread_t, t2);
            // Returns nonzero value if t1 and t2 are equal, otherwise 0

5. Joining

为了确保 thread 之间 terminate 的顺序,可以用 pthread_join()

#include <pthread.h>

int pthread_join(pthread_t thread, void **retval);
            // Returns 0 on sucess, or a positive error number on error

代表 thread 执行完之後,自己 (main thread) 才会结束
这是为了避免 main thread) 都结束了,还留下一些 zombie process

6. Detaching a thread

另一种避免 zombie process 的方式,可一把一个 thread 给杀掉

#include <pthread.h>

int pthread_detach(pthread_t thread);
            // Returns 0 on sucess, or a positive error number on error

可以把 thread 给杀掉

7. 程序码范例


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

static void *
threadFunc(void *arg)
{
    char *s = (char *) arg;

    printf("%s", s);

    return  (void *) strlen(s);
}

int
main (int argc, char **argv)
{
    pthread_t t1;
    void *res;
    int s;

    s = pthread_create(&t1, NULL, threadFunc, "Hello world\n");
    if (s != 0) {
        fprintf(stderr, "error\n");
        exit(EXIT_FAILURE);
    }

    printf("Message from main()\n");
    s = pthread_join(t1, &res);
    if (s != 0) {
        fprintf(stderr, "error\n");
        exit(EXIT_FAILURE);
    }

    printf("%hread returned $ld\nk", (long) res);
    
    exit(EXIT_SUCCESS);
}

8. 参考资料

The Linux Programming Interface


<<:  【Day 6】机器学习基本功(四)

>>:  Day 19 - 写一个含状态的 Button

[第七只羊] 迷雾森林舞会前夕 建立使用者关联

天亮了 昨晚是平安夜 关於迷雾森林故事 秘密通道 Rocky 循着发光的脚印继续寻找爸爸妈妈的下落 ...

Alpine Linux Porting (1.99) ES LEBT !!!

惯例先上成果图XD https://asciinema.org/a/439607 终於开机开到she...

# Day 28 Page Migration (三)

文件 原文文件:Page migration 翻译: Non-LRU 分页迁移 ==========...

Day4 VPC & Security Group

从地端 On-Premise的传统资讯部署,再到云端 Cloud的新形态部署模式,在这个转型过程初...

JS 44 - 输入网址就能使用的 RSS 阅读器

大家好! 今天要实作能输入网址的 RSS 阅读器。 我们进入今天的主题吧! 程序码 Felix('f...