Looking for pthreads Answers? Try Ask4KnowledgeBase
Looking for pthreads Keywords? Try Ask4Keywords

pthreads開始使用pthreads


備註

本節概述了pthreads是什麼,以及開發人員可能想要使用它的原因。

它還應該提到pthreads中的任何大型主題,並鏈接到相關主題。由於pthreads的文檔是新的,您可能需要創建這些相關主題的初始版本。

安裝或設置

有關設置或安裝pthread的詳細說明。

使用pthreads的最小“Hello World”

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

/* function to be run as a thread always must have the same signature:
   it has one void* parameter and returns void */
void *threadfunction(void *arg)
{
  printf("Hello, World!\n"); /*printf() is specified as thread-safe as of C11*/
  return 0;
}

int main(void)
{
  pthread_t thread;
  int createerror = pthread_create(&thread, NULL, threadfunction, NULL);
  /*creates a new thread with default attributes and NULL passed as the argument to the start routine*/
  if (!createerror) /*check whether the thread creation was successful*/
    {
      pthread_join(thread, NULL); /*wait until the created thread terminates*/
      return 0;
    }
  fprintf("%s\n", strerror(createerror), stderr);
  return 1;
}
 

將參數傳遞給線程

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

void *thread_func(void *arg)
{
    printf("I am thread #%d\n", *(int *)arg);
    return NULL;
}

int main(int argc, char *argv[])
{
    pthread_t t1, t2;
    int i = 1;
    int j = 2;

    /* Create 2 threads t1 and t2 with default attributes which will execute
    function "thread_func()" in their own contexts with specified arguments. */
    pthread_create(&t1, NULL, &thread_func, &i);
    pthread_create(&t2, NULL, &thread_func, &j);

    /* This makes the main thread wait on the death of t1 and t2. */
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    printf("In main thread\n");
    return 0;
}
 

如何編譯:

$ gcc -pthread -o hello hello.c
 

這打印:

I am thread #1
I am thread #2
In main thread
 

從線程返回結果

指向具體數據類型的指針(轉換為void * )可用於將值傳遞給線程函數並返回結果。

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

struct thread_args
{
    int a;
    double b;
};


struct thread_result
{
    long x;
    double y;
};

void *thread_func(void *args_void)
{
    struct thread_args *args = args_void;
    /* The thread cannot return a pointer to a local variable */
    struct thread_result *res = malloc(sizeof *res);

    res->x  = 10 + args->a;
    res->y = args->a * args->b;
    return res;
}

int main()
{
    pthread_t threadL;
    struct thread_args in = { .a = 10, .b = 3.141592653 };
    void *out_void;
    struct thread_result *out;

    pthread_create(&threadL, NULL, thread_func, &in);
    pthread_join(threadL, &out_void);
    out = out_void;
    printf("out -> x = %ld\tout -> b = %f\n", out->x, out->y);
    free(out);

    return 0;
}
 

在許多情況下,不必以這種方式傳遞返回值 - 例如,參數struct中的空格也可用於返回結果,或者指向共享數據結構的指針可以傳遞給線程並且結果存儲在那裡。