2025/03/25

C++ Thread

Pthreads

POSIX Threads 是 POSIX 的執行緒標準,定義了建立和操控執行緒的一套API。

Process 和 Threads 之間的不同點:

  • Process:
    A process is a program placed in memory or running with all the run-time environment (or all the resources) associated with it.
  • Thread:
    A thread is a portion or part of the process and the smallest sequential unit of instructions processed independently by the scheduler of the operating system.
    It is simply an execution or processing unit composed of a set of instructions contained in the process.

Process 之間的資源是隔離的,而同一個 Process 內的 Thread 之間的記憶體資源是共用的,所以使用 Thread 需要小心的處理全域變數, 需要使用互斥鎖(Mutex)等完成執行緒之間的同步管理。 除了共同的記憶體,執行緒區域儲存區(Thread Local Storage,TLS) 可以讓執行緒有私人的資料儲存區,讓執行緒可以儲存各自執行緒的資料。

Pthreads API 全都以 "pthread_" 開頭,並可以分為四類:

  • 執行緒管理,例如建立執行緒,等待(join)執行緒,查詢執行緒狀態等。
  • 互斥鎖(Mutex):建立、摧毀、鎖定、解鎖、設定屬性等操作
  • 條件變數(Condition Variable):建立、摧毀、等待、通知、設定與查詢屬性等操作
  • 使用了互斥鎖的執行緒間的同步管理

下面是使用的例子:

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

static void wait(void) {
    time_t start_time = time(NULL);

    while (time(NULL) == start_time) {
        /* do nothing except chew CPU slices for up to one second */
    }
}

static void *thread_func(void *vptr_args) {
    int i;

    for (i = 0; i < 20; i++) {
        fputs("  b\n", stderr);
        wait();
    }

    return NULL;
}

int main(void) {
    int i;
    pthread_t thread;

    if (pthread_create(&thread, NULL, thread_func, NULL) != 0) {
        return EXIT_FAILURE;
    }

    for (i = 0; i < 20; i++) {
        puts("a");
        wait();
    }

    if (pthread_join(thread, NULL) != 0) {
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

建立執行緒的函式如下:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

執行緒屬性 pthread_attr_t 可以設定 __detachstate,表示新執行緒是否與行程中其他執行緒脫離同步。 如果設定為 PTHREAD_CREATE_DETACHED,則新執行緒不能用 pthread_join() 來同步,且在退出時自行釋放所占用的資源。 預設為 PTHREAD_CREATE_JOINABLE 狀態。也可以先建立執行緒並執行以後用 pthread_detach() 來設定。 一旦設定為 PTHREAD_CREATE_DETACHED 狀態,不論是建立時設定還是執行時設定,都不能再恢復到 PTHREAD_CREATE_JOINABLE 狀態。

C++ Thread

自 C++11 開始,C++ 標準函式庫提供了 Thread library。

下面就是一個使用的例子。

#include <iostream>
#include <thread>

void myfunc() { std::cout << "At myfunc..." << std::endl; }

int main() {
    std::thread t1(myfunc);

    std::this_thread::sleep_for(std::chrono::seconds(1));

    t1.join();
    return 0;
}

參考連結

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。