1.建立线程:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
用法:#include <pthread.h>
功能:创建线程(实际上就是确定调用该线程函数的入口点),在线程创建以后,就开始运行相关的线程函数。
说明:thread:线程标识符;
attr:线程属性设置;一般用NUll就可以了;
start_routine:线程函数的起始地址;
arg:传递给start_routine的参数,就是该函数传递参数给线程的函数;
返回值:成功,返回0;出错,返回-1。
2.pthread_t pthread_join(pthread_t pthreadID,void *reval[])
功能:等待进程指定的线程,直至该线程结束。
参数:pthreadID:指定的线程;
reval:线程结束时的返回值;
3.pthread_t exit(void* reval);
功能:结束线程;
参数:reval:结束线程时的返回值;该函数返回给pthread_t pthread_join()的reval参数;
应用举例:
#include<stdio.h>
#include<pthread.h>
void *pthread_funtion(void* arg<span style="font-family: Arial, Helvetica, sans-serif;">);</span>
int main()
{
char messg[]="hello world!";
void *retval;
pthread_t mypthread;
if(pthread_create(&mypthread,NULL,pthread_funtion,(void*)messg)==0)
printf("create pthread success\n");
pthread_join(&mypthread,&retval);
printf("get result:%s\n",(char*)retval);//注意对传参进行转换
return 0;
}
void *pthread_funtion(void* arg)
{
printf("get message:%s\n",(char*)arg);//注意:对传参进行转换:
pthread_exit("Good Bye!");
}
执行结果为:
[root@localhost ~]# ./pthread_creat
create pthread success
get message:hello world!
get result:Good Bye!
建立多线程:
举例:
#include<stdio.h>
#include<pthread.h>
void *pthread_funtion(void* arg);
int main()
{
pthread_t mypthread[3];//欲建立3个线程
int i;
for(i=0;i<3;i++)
pthread_create(&mypthread[i],NULL,pthread_funtion,(void*)i);
while(1);
return 0;
}
void *pthread_funtion(void* arg)
{
int i;
for(i=0;i<5;i++)
printf("pthread num:%d\n",(int)arg);//注意:对传参进行转换,没有*了:
}
以上运行情况:打印出的线程号顺序混乱。无法向预期那样打印输出;这样以后,执行语句的先后顺序,不可预估了;所以需要考虑线程同步了;
互斥mutex:
1)动态设置mutex:
int pthread_mutex_init(pthread_mutex,const pthread_mutex_attr *attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
2)静态设置互斥:
pthread_mutex_t fastmutex=PTHREAD_MUTEX_INITIALIZER;
锁定:(用于锁住线程)
pthread_mutex_lock(pthread_mutex_t *mutex);
pthread_mutex_unlock(pthread_mutex_t *mutex);
互斥应用举例:
#include<stdio.h>
#include<pthread.h>
void *pthread_funtion(void* arg);
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;//静态互斥;
int main()
{
pthread_t mypthread[3];//欲建立3个线程
int i;
for(i=0;i<3;i++)
pthread_create(&mypthread[i],NULL,pthread_funtion,(void*)i);
while(1);
return 0;
}
void *pthread_funtion(void* arg)
{
pthread_mutex_lock(&mymutex);//锁住函数体就可以了;
int i;
for(i=0;i<5;i++)
printf("pthread num:%d\n",(int)arg);//注意:对传参进行转换,没有*了:
pthread_mutex_unlock(&mymutex);
}
运行结果:[root@localhost ~]# ./pthread_lock
pthread num:2
pthread num:2
pthread num:2
pthread num:2
pthread num:2
pthread num:1
pthread num:1
pthread num:1
pthread num:1
pthread num:1
pthread num:0
pthread num:0
pthread num:0
pthread num:0
pthread num:0