me icon indicating copy to clipboard operation
me copied to clipboard

学习 C++ (Part 10: 多线程)

Open nonocast opened this issue 2 years ago • 0 comments

线程的实现本质上都是依赖于操作系统,所谓的跨平台是对具体的抽象,Windows上使用CreateThread,linux (POSIX) 上使用pthread, macOS上使用NSThread或是GCD, 因为macOS是POSIX所以也可以使用pthread,C++11也提供了std::thread这个就支持跨平台,但风评不太好。

参考obs,我们选择先看下pthread。

main.c

#include <pthread.h>
#include <signal.h>
#include <stdbool.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>

void *worker(void *arg);
void teardown(int s);

pthread_t thread1;
bool shutdown;

int main(int argc, char *argv[]) {
  signal(SIGINT, teardown);

  // get current thread id
  pthread_t thread0 = pthread_self();
  printf("main thread: %lu\n", (unsigned long) thread0);

  pthread_create(&thread1, NULL, &worker, NULL);

  while (true) {
    sleep(1);
  }
  printf("main exit.");

  return 0;
}

void *worker(void *arg) {
  pthread_t self = pthread_self();
  printf("worker thread: %lu\n", (unsigned long) worker);

  while (!shutdown) {
    printf("%u\n", (unsigned int) time(NULL));
    sleep(1);
  }
  printf("worker killed\n");
  return NULL;
}

void teardown(int s) {
  printf("\nSIGINT\n");
  shutdown = true;
  pthread_join(thread1, NULL);
  printf("exit\n");
  _exit(0);
}

程序很简单,意图是通过main启动worker线程,然后等到SIGINT(command-c)时发出终止“信号”,worker接收后正确回收资源后退出,main通过join正常退出的过程。

运行的输出如下:

➜  build ./app
main thread: 8601851392
worker thread: 4305890896
1651163208
1651163209
1651163210
1651163211
1651163212
1651163213
^C
SIGINT
worker killed
exit

参考阅读:

nonocast avatar Apr 28 '22 16:04 nonocast