POSIX线程库头文件:<pthread.h>
编译引用库 -pthread
1、创建线程
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void*), void *restrict arg);
第一个参数pthread_t,当创建成功后,作为线程的操作“句柄”(Linux大虾别见笑。。。)
第二个参数pthread_attr_t,是线程的属性,低级应用中,可以置为NULL
地三个参数为函数指针,就是调用的线程函数(线程就跑这个函数)
如下写这个函数
void *function(void *param)
{
.....
}
第四个参数,传入线程函数的参数
2、主线程等待子线程
int pthread_join(pthread_t thread, void **value_ptr);
第一个参数就是刚才成功创建线程的句柄,
第二个参数,是线程返回的值
当然,这个“返回”不是线程的return,
在线程函数中如下可以返回给value_ptr
void *thread_function(void *param)
{
pthread_exit((void*)"This is the return value");
}
-----------------------------------------------------------------------------------------------------------------------------
针对上述1和2的代码
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void *function(void * param)
{
printf("In the thread ! \n");
printf("The param is %s\n",param);
sleep(2);
printf("Thread end\n");
pthread_exit("xiexie");
}
int main()
{
pthread_t p_t;
pthread_attr_t p_a;
char * msg = "Hello ,thread ! ";
void * ret;
int res = pthread_create(&p_t,NULL,function,(void *)msg);
if(res)
{
printf("Thread create fail.");
exit(EXIT_FAILURE);
}
res = pthread_join(p_t,&ret);
if(res)
{
printf("thread join fail.\n");
exit(EXIT_FAILURE);
}
printf("Thread join.return %s\n",(char *)ret);
printf("main exit.\n");
return 0;
}
-----------------------------------------------------------------------------------------------------------------------------
4、互斥量---锁同步
代码:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define MAX_THREAD 30
int global = 100;
pthread_mutex_t mut;
void *function(void *param)
{
int i,j;
for(i=0;i<1000;i++)
{
for(j=0;j<1000;j++)
{
pthread_mutex_lock(&mut);
global++;
global--;
pthread_mutex_unlock(&mut);
}
}
}
int main()
{
pthread_t p_t[MAX_THREAD];
int i;
pthread_mutex_init(&mut,NULL);
for(i=0;i<MAX_THREAD;i++)
{
int res = pthread_create(&p_t[i],NULL,function,NULL);
if(res)
{
printf("Thread %d create fail.\n",i);
}
}
for(i=MAX_THREAD-1;i>=0;i--)
{
pthread_join(p_t[i],NULL);
}
printf("%d",global);
return 0;
}