理解線程1 C語言示例的程序

一個簡單的C語言實現的線程示例

在看《Beginning Linux Programming》時,爲了更好的理解線程的概念,書中列舉了這樣一個小例子:python

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

void *thread_function(void *arg);
char message[] = "Hello World";

int main() {
  int res;
  pthread_t a_thread;
  void *thread_result;

  res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
  if (res != 0) {
    perror("Thread creation failed");
    exit(EXIT_FAILURE);
  }
  printf("Waiting for thread to finish...\n");
  res = pthread_join(a_thread, &thread_result);
  if (res != 0) {
    perror("thread join failed");
    exit(EXIT_FAILURE);
  }
  printf("Thread joined, it returned %s\n", (char *)thread_result);
  printf("Message is now %s\n", message);
  exit(EXIT_SUCCESS);
}

void *thread_function(void *arg) {
  printf("thread_function is running, Argument was %s\n", (char *)arg);
  sleep(3);
  strcpy(message, "Bye!");
  pthread_exit("Thank you for the CPU time");
}

將程序編譯連接後運行,能夠看到下面這樣的結果數組

➜  chapter12 ./thread
Waiting for thread to finish...
thread_function is running, Argument was Hello World
Thread joined, it returned Thank you for the CPU time
Message is now Bye!

這裏使用 pthread_create 建立新線程, pthread_create 的定義以下:函數

#include <pthread.h>

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

根據 pthread_create 要求, thread_function 只有一個指向void的指針做爲參數,返回的也是指向void的指針。
當建立新的線程後,新線程在 thread_function 中開始執行,打印本身的參數。
原有線程在確保新線程啓動後調用 pthread_join 函數等到線程結束,而且將新線程的返回值存在 thread_result 指針裏。
新線程能夠直接訪問 message 數組變量,若是是調用 fork() 的話就沒有這種效果。線程

python也提供了處理線程相關的 thread 和 基於它上面抽象的 threading 等模塊,將在之後的文章中探究。指針

不禁感慨,若是很少懂一些C語言,那麼很難提升本身Python水平啊。code

相關文章
相關標籤/搜索