iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0
自我挑戰組

C 語言筆記系列 第 8

[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


上一篇
[C 語言筆記--Day07] 如何用 C 語言實作一個泛型物件
下一篇
[C 語言筆記--Day09] 解題紀錄:Moamen and k-subarrays
系列文
C 語言筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言