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函数的第一个参数是阻塞的线程的标识符,第二个参数是返回值。
C/C++ POSIX线程学习一
最新推荐文章于 2024-09-24 23:44:20 发布