Linux中和POSIX标准

Linux的API是遵循POSIX标准的
POSIX表示可移植操作系统接口(Portable Operating System Interface of UNIX,缩写为 POSIX ),POSIX标准定义了操作系统应该为应用程序提供的接口标准,是IEEE为要在各种UNIX操作系统上运行的软件而定义的一系列API标准的总称,其正式称呼为IEEE 1003,而国际标准名称为ISO/IEC 9945。

多线程

#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
 void *thread_function(void *arg) {
  int i;
  for ( i=0; i<20; i++) {
    printf("Thread says hi!\n");
    sleep(1);
  }
  return NULL;
}
int main(void) {
  pthread_t mythread;

  if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
    printf("error creating thread.");
    abort();
  }
  if ( pthread_join ( mythread, NULL ) ) {
    printf("error joining thread.");
    abort();
  }
  exit(0);
}

常见posix API如下

  • pthread_create():创建一个线程
  • pthread_exit():终止当前线程
  • pthread_cancel():中断另外一个线程的运行
  • pthread_join():阻塞当前的线程,直到另外一个线程运行结束
  • pthread_attr_init():初始化线程的属性
  • pthread_attr_setdetachstate():设置脱离状态的属性(决定这个线程在终止时是否可以被结合)
  • pthread_attr_getdetachstate():获取脱离状态的属性
  • pthread_attr_destroy():删除线程的属性
  • pthread_kill():向线程发送一个信号

如果你想让自己的代码在posix平台上保持兼容,请使用上述API。而不要使用linux特有的如clone这样的API。

猜你喜欢

转载自blog.csdn.net/define_us/article/details/81983114
今日推荐