1.互斥机制代码
#include<myhead.h>
char ikun[128]="";
//创建互斥锁
pthread_mutex_t mutex;
void *task(void*argc)
{
while(1)
{
//上锁
pthread_mutex_lock(&mutex);
printf("%s\n",ikun);
strcpy(ikun,"我是真爱坤\n");
//释放
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, const char *argv[])
{
pthread_t tid;
//创建互斥锁
pthread_mutex_init(&mutex,NULL);
if(pthread_create(&tid,NULL,task,NULL)!=0)
{
printf("ggg");
return -1;
}
//主线程
while(1)
{
//上锁
pthread_mutex_lock(&mutex);
printf("%s\n",ikun);
strcpy(ikun,"我是小黑子\n");
//释放
pthread_mutex_unlock(&mutex);
}
//阻碍回收
pthread_join(tid,NULL);
//摧毁
pthread_mutex_destroy(&mutex);
return 0;
}
2.同步机制
#include<myhead.h>
//1、创建一个无名信号量
sem_t sem;
void *task1(void *arg)
{
while(1)
{
sleep(2);
printf("我是小黑子\n");
//释放资源
sem_post(&sem);
}
}
void *task2(void *arg)
{
while(1)
{
//申请资源
sem_wait(&sem);
printf("我是真ikun\n");
}
}
int main(int argc, const char *argv[])
{
//创建两个线程
pthread_t tid1,tid2;
//初始化无名信号量
sem_init(&sem, 0, 0);
if(pthread_create(&tid1, NULL, task1, NULL) != 0)
{
printf("tid1 create error\n");
return -1;
}
if(pthread_create(&tid2, NULL, task2, NULL) != 0)
{
printf("tid2 create error\n");
return -1;
}
//回收资源
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
//销毁无名信号量
sem_destroy(&sem);
return 0;
}
3.使用三个线程完成两个文件的拷贝,线程1完成拷贝前一半,线程2完成拷贝后一半,主线程回收两个分支线程的资源
4.使用三个线程完成:线程1输出字符‘A’,线程2输出字符‘B',线程3输出字符’C‘,要求输出结果为:ABCABCABCACB......
#include<myhead.h>
char ikun[128]="";
//创建无名信号量
sem_t sem1,sem2;
void *task1(void *arg)
{
while(1)
{
printf("A");
//释放资源
sem_post(&sem1);
sem_post(&sem2);
}
}
void *task2(void *arg)
{
while(1)
{
//申请资源
sem_wait(&sem1);
printf("B");
}
}
int main(int argc, const char *argv[])
{
pthread_t pid1,pid2;
//初始化无名信号量
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
if(pthread_create(&pid1,NULL,task1,NULL)!=0)
{
printf("ggggg");
return -1;
}
if(pthread_create(&pid2,NULL,task2,NULL)!=0)
{
printf("gggg");
return -1;
}
while(1)
{
sem_wait(&sem2);
printf("C");
}
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
//摧毁无名信号量
sem_destroy(&sem1);
sem_destroy(&sem2);
return 0;
}