如何利用pthread_t實(shí)現(xiàn)并發(fā)控制

小樊
82
2024-09-05 15:32:33

pthread_t 是 POSIX 線程庫(kù)中表示線程的數(shù)據(jù)類型

  1. 包含頭文件:在你的源代碼文件中,需要包含 <pthread.h> 頭文件。
#include <pthread.h>
  1. 定義線程函數(shù):創(chuàng)建一個(gè)線程函數(shù),該函數(shù)將在新線程中運(yùn)行。線程函數(shù)應(yīng)該接受一個(gè) void * 類型的參數(shù),并返回一個(gè) void * 類型的值。
void *thread_function(void *arg) {
    // 在這里編寫你的線程執(zhí)行代碼
    return NULL;
}
  1. 創(chuàng)建線程變量:定義一個(gè) pthread_t 類型的變量,用于存儲(chǔ)線程的 ID。
pthread_t thread_id;
  1. 創(chuàng)建線程:使用 pthread_create() 函數(shù)創(chuàng)建一個(gè)新線程。該函數(shù)需要三個(gè)參數(shù):指向線程 ID 的指針、線程屬性(通常為 NULL)和線程函數(shù)的地址。
int result = pthread_create(&thread_id, NULL, thread_function, NULL);
if (result != 0) {
    printf("Error creating thread: %d\n", result);
    exit(1);
}
  1. 等待線程結(jié)束(可選):如果你需要等待線程完成其任務(wù),可以使用 pthread_join() 函數(shù)。該函數(shù)需要兩個(gè)參數(shù):線程 ID 和一個(gè)指向 void * 類型的指針,用于存儲(chǔ)線程函數(shù)的返回值。
void *return_value;
int result = pthread_join(thread_id, &return_value);
if (result != 0) {
    printf("Error joining thread: %d\n", result);
    exit(1);
}
  1. 使用互斥鎖或其他同步原語(yǔ)來(lái)實(shí)現(xiàn)并發(fā)控制。例如,使用 pthread_mutex_t 類型的互斥鎖來(lái)保護(hù)共享資源。
#include <pthread.h>
#include<stdio.h>
#include <stdlib.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shared_counter = 0;

void *thread_function(void *arg) {
    for (int i = 0; i < 100000; i++) {
        pthread_mutex_lock(&mutex);
        shared_counter++;
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() {
    const int NUM_THREADS = 10;
    pthread_t threads[NUM_THREADS];

    for (int i = 0; i < NUM_THREADS; i++) {
        int result = pthread_create(&threads[i], NULL, thread_function, NULL);
        if (result != 0) {
            printf("Error creating thread: %d\n", result);
            exit(1);
        }
    }

    for (int i = 0; i < NUM_THREADS; i++) {
        void *return_value;
        int result = pthread_join(threads[i], &return_value);
        if (result != 0) {
            printf("Error joining thread: %d\n", result);
            exit(1);
        }
    }

    printf("Shared counter: %d\n", shared_counter);
    return 0;
}

這個(gè)示例展示了如何使用 pthread_t、互斥鎖和其他 POSIX 線程函數(shù)來(lái)實(shí)現(xiàn)并發(fā)控制。注意,這個(gè)示例僅用于演示目的,實(shí)際應(yīng)用中可能需要更復(fù)雜的錯(cuò)誤處理和資源管理。

0