溫馨提示×

c語言線程創(chuàng)建的方式有哪些

小億
109
2023-11-28 16:42:22
欄目: 編程語言

C語言中線程的創(chuàng)建方式有以下幾種:

  1. pthread_create函數(shù):該函數(shù)是POSIX標準中用于創(chuàng)建線程的函數(shù)。需要包含頭文件pthread.h,并傳入線程標識符指針、線程屬性、線程入口函數(shù)以及入口函數(shù)的參數(shù)。示例代碼如下:
#include <pthread.h>

void* thread_func(void* arg) {
    // 線程執(zhí)行的代碼
}

int main() {
    pthread_t thread;
    pthread_create(&thread, NULL, thread_func, NULL);
    // ...
    return 0;
}
  1. _beginthread和_beginthreadex函數(shù):這是Windows下用于創(chuàng)建線程的函數(shù)。需要包含頭文件process.h,并傳入線程入口函數(shù)以及入口函數(shù)的參數(shù)。示例代碼如下:
#include <process.h>

unsigned int __stdcall thread_func(void* arg) {
    // 線程執(zhí)行的代碼
    return 0;
}

int main() {
    unsigned int thread;
    _beginthreadex(NULL, 0, thread_func, NULL, 0, &thread);
    // ...
    return 0;
}
  1. 創(chuàng)建線程時指定函數(shù)指針:使用函數(shù)指針來作為線程的入口函數(shù),然后在主函數(shù)中通過調(diào)用該函數(shù)來創(chuàng)建線程。示例代碼如下:
#include <stdio.h>

void thread_func(void* arg) {
    // 線程執(zhí)行的代碼
}

int main() {
    void (*ptr)(void*) = &thread_func;
    pthread_create(&thread, NULL, ptr, NULL);
    // ...
    return 0;
}

這些都是常見的C語言線程創(chuàng)建方式,具體選擇哪種方式取決于開發(fā)環(huán)境和需求。

0