C/C++ POSIX线程学习一

POSIX线程是一种可移植的多线程代码
pthread_t类型在LinuxThreads中定义为无符号长整型;
pthread_t pthread_self(void) 本函数返回本线程的ID。进程ID在整个系统中是唯一的,但线程不同,线程ID只在它所属的进程环境中有效.
int pthread_equal(pthread_t thread1, pthread_t thread2) 判断两个线程描述符是否指向同一线程;
thread1.c
#include <stdio.h>
#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);
}
 此例中首先定义变量mythread,类型是pthread;创建线程,第一个参数&mythread是指向变量mythread的指针,第二个参数NULL是用来定义线程的属性,此处为缺省即为默认属性,第三个参数是线程创建时调用的函数thread_function,此函数在上面有定义,在i<20的情况下,打印20次Thread says hi!
第四个参数是向线程传递的参数,此处为空,如果线程创建成功,返回值为0,则不执行下面的打印语句和异常终止函数abort(正确创建线程就不用异常终止了),在创建函数时执行调用函数thread_function,用pthread_join来阻塞其他进程,直到这个进程完成,才开放这个阻塞,pthread_join函数的第一个参数是阻塞的线程的标识符,第二个参数是返回值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值