pthread_create用于创建一个线程,成功返回0,否则返回Exxx(为正数)。
pthread_t *tid:线程id的类型为pthread_t,通常为无符号整型,当调用pthread_create成功时,通过*tid指针返回。 const pthread_attr_t *attr:指定创建线程的属性,如线程优先级、初始栈大小、是否为守护进程等。可以使用NULL来使用默认值,通常情况下我们都是使用默认值。 void *(*func) (void *):函数指针func,指定当新的线程创建之后,将执行的函数。 void *arg:线程将执行的函数的参数。如果想传递多个参数,请将它们封装在一个结构体中。pthread_join用于等待某个线程退出,成功返回0,否则返回Exxx(为正数)。
pthread_t tid:指定要等待的线程ID void ** status:如果不为NULL,那么线程的返回值存储在status指向的空间中(这就是为什么status是二级指针的原因!这种才参数也称为“值-结果”参数)。pthread_self用于返回当前线程的ID。
pthread_detach用于是指定线程变为分离状态,就像进程脱离终端而变为后台进程类似。成功返回0,否则返回Exxx(为正数)。变为分离状态的线程,如果线程退出,它的所有资源将全部释放。而如果不是分离状态,线程必须保留它的线程ID,退出状态直到其它线程对它调用了pthread_join。
进程也是类似,这也是当我们打开进程管理器的时候,发现有很多僵死进程的原因!也是为什么一定要有僵死这个进程状态。
pthread_exit用于终止线程,可以指定返回值,以便其他线程通过pthread_join函数获取该线程的返回值。
知道了这些函数之后,我们试图来完成本文一开始的问题:
1)有一int型全局变量g_Flag初始值为0;
2)在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1
3)在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2
这3点很简单嘛!!!不就是调用pthread_create创建线程。代码如下:
/*
* 1)有一int型全局变量g_Flag初始值为0;
*
* 2)在主线称中起动线程1,打印“this is thread1”,并将g_Flag设置为1
*
* 3)在主线称中启动线程2,打印“this is thread2”,并将g_Flag设置为2
*
*/
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<errno.h>
#include<unistd.h>
int g_Flag=0;
void* thread1(void*);
void* thread2(void*);
/*
* when program is started, a single thread is created, called the initial thread or main thread.
* Additional threads are created by pthread_create.
* So we just need to create two thread in main().
*/
int main(int argc, char** argv)
{
printf("enter mainn");
pthread_t tid1, tid2;
int rc1=0, rc2=0;
rc2 = pthread_create(&tid2, NULL, thread2, NULL);
if(rc2 != 0)
printf("%s: %dn",__func__, strerror(rc2));
rc1 = pthread_create(&tid1, NULL, thread1, &tid2);
if(rc1 != 0)
printf("%s: %dn",__func__, strerror(rc1));
printf("leave mainn");
exit(0);
}
/*
* thread1() will be execute by thread1, after pthread_create()
* it will set g_Flag = 1;
*/
void* thread1(void* arg)
{
printf("enter thread1n");
printf("this is thread1, g_Flag: %d, thread id is %un",g_Flag, (unsigned int)pthread_self());
g_Flag = 1;
printf("this is thread1, g_Flag: %d, thread id is %un",g_Flag, (unsigned int)pthread_self());
printf("leave thread1n");
pthread_exit(0);
}
/*
* thread2() will be execute by thread2, after pthread_create()
* it will set g_Flag = 2;
*/
void* thread2(void* arg)
{
printf("enter thread2n");
printf("this is thread2, g_Flag: %d, thread id is %un",g_Flag, (unsigned int)pthread_self());
g_Flag = 2;
printf("this is thread1, g_Flag: %d, thread id is %un",g_Flag, (unsigned int)pthread_self());
printf("leave thread2n");
pthread_exit(0);
}








