需要引用头文件 <pthread.h>
pthread_create(&thread1,NULL,(void *)&dealfunction,NULL); //创建线程
thread1声明格式:pthread_t thread1。
NULL:表示线程属性的指针,可默认为NULL。
dealfunction声明格式:void dealfunction()。返回值可以为其它,可以有参数。
NULL:处理函数的参数指针。
pthread_join(thread1,NULL); //阻塞当前线程,立即执行线程1。
pthread_mutex_init(&mutex1,NULL); //初始化互斥锁
mutex1声明格式:pthread_mutex_t mutex1。
NULL:互斥锁属性。
pthread_mutex_destroy(&mutex1); //释放锁资源。
pthread_mutex_lock(&mutex1); //加锁
pthread_mutex_unlock(&mutex1); //去锁
在代码中使用pthread,进行编译时,需要使用命令 gcc -o hello hello.c -lpthread。
-lpthread 必须要有,否则会报 undefined reference to 'pthread_create'等错误。
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int i;
pthread_mutex_t mutex1;
void readfunction();
void writefunction();
int main()
{
pthread_t thread1,thread2;
i = 0;
pthread_mutex_init(&mutex1,NULL);//初始化互斥锁
pthread_create(&thread1,NULL,(void *)&readfunction,NULL);//创建一个新线程
pthread_create(&thread2,NULL,(void *)&writefunction,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);//等待线程2执行完
pthread_mutex_destroy(&mutex1);//释放互斥锁
return 0;
}
void readfunction()
{
while(1)
{
usleep(1500000);//单位微秒,睡眠是为了写线程拥有锁的机会
if(i >= 10)
break;
pthread_mutex_lock(&mutex1);
printf("%d\n",i);
pthread_mutex_unlock(&mutex1);
}
}
void writefunction()
{
while(i < 10)
{
pthread_mutex_lock(&mutex1);
i++;
pthread_mutex_unlock(&mutex1);
usleep(2000000);
}
}