pthread

来自百合仙子's Wiki
跳转到导航 跳转到搜索

函数

pthread_create 用来创建新的线程。使用它需要包含 pthread.h 文件。其第三个参数为返回值为 void* 的函数。

pthread_join 可以用来等待线程退出,否则主线程退出时整个程序会退出。

示例

我写的测试程序:

//=====================================================================
// 多线程测试
//=====================================================================
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
//---------------------------------------------------------------------
void* thread2(){
  while(1){
    printf("Hello from thread2!\n");
    sleep(3);
  }
}
int main(){
  pthread_t pid;
  pthread_create(&pid, NULL, thread2, NULL);
  printf("Hello from main()!\n");
  sleep(9);

  return 0;
}
//=====================================================================

linux c/c++多线程程序的编写 中的示例程序(有少许更改):

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.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 (0 != res) {
        perror("Thread creation faied");
        exit(EXIT_FAILURE);
    }
 
    printf("Waiting for thread to finish...\n");
    res = pthread_join(a_thread, &thread_result);
    if (0 != res) {
        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");
}

编译

编译命令:

gcc -o mthread mthread.c -lpthread

外部链接