//首先线程同步有几种方式, 互斥量,信号量,条件
//互斥量的目的是保护一段临界区,而不是用来调整主线程和所创建线程的执行顺序
//用在当一个线程的访问临界区时会对另一个线程的访问有影响,所以使用互斥锁
//另外互斥锁的初始化时,没有设置其属性,这样的话线程无法递归加锁,需要递归的时候就要设置互斥锁的属性,使用pthread_mutexattr_t
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int *fun(int *i);
//创建线程锁, 本例子创建线程锁意义不大,只是用来说明其用法
pthread_mutex_t mymutex; //在main函数外创建,这样线程函数才能访问到,初始化在main中就可以了
int main()
{
int res;
void *pthread_result; //用来获取线程的返回值
int i = 0;
res = pthread_mutex_init(&mymutex,NULL);
if(0 != res)
{
perror("mutex init error\n");
}
//创建新线程
pthread_t mythread;
res = pthread_create(&mythread, NULL, fun, &i); //第三个和第四个属性可是是任何类型的指针
if(0 != res)
{
perror("create thread error\n");
}
int x_main = 0;
pthread_mutex_lock(&mymutex);
for(;x_main< 500;x_main++)
printf("now number is %d\n",i++);
pthread_mutex_unlock(&mymutex);
//等待线程结束
res = pthread_join(mythread, &pthread_result);// 一种观点认为, 这个函数会导致主线程阻塞
if(0 != res)
{
perror("join failed\n");
}
//锁使用完成后, 释放锁资源
pthread_mutex_destroy(&mymutex);
printf("the number of i is: %d\n", i);
printf("thread return: %s\n",pthread_result);
return 0;
}
//
int *fun(int *i)
{
int x_thread = 0;
pthread_mutex_lock(&mymutex);
for(;x_thread< 500;x_thread++)
printf("now number is %d\n",(*i)++);
pthread_mutex_unlock(&mymutex);
pthread_exit("the thread has exit");
}