第一个线程的程序

#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);
  }
}

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");
}

玩转线程,需要了解以下函数:

1,怎么创建一个新的线程:

#include <pthread.h>

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

看起来,挺吓人的,但是实际用起来,是非常简单,第一个参数是指向pthread_t的指针,当线程被创建起来的时候,这个

就相当于一个标识符,使得你可以去引用这个线程,接下来第二个参数,设置线程的属性,最后两个参数,告诉线程

函数开始运行的地方以及传到这个函数的参数。


void *(*start_routine)(void *)


前面这一行,也就是说传进去的函数,返回一个指向void 的指针,其传进去的参数也是指向void 的指针所以,可以传任意类型作为参数,可以返回一个指针指向任意类型。


如果返回0, 表示创建成功。

猜你喜欢

转载自blog.csdn.net/robinsongsog/article/details/79982232