互斥锁的小例程
来源:互联网 发布:乐高星球大战atst淘宝 编辑:程序博客网 时间:2024/04/27 14:37
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
void *thread_function(void *argc);
pthread_mutex_t work_mutex;
#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int time_to_exit = 0;
int main(int argc, char *argv[])
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&work_mutex, NULL); //对互斥锁进行初始化
if (res != 0)
{
perror ("Mutex initialization failed!\n");
exit (-1);
}
res= pthread_create(&a_thread, NULL, thread_function, NULL);
if (res != 0)
{
perror ("Thread created failed !\n");
exit (-1);
}
pthread_mutex_lock(&work_mutex);
printf ("Input some text. Enter 'end' to finish\n");
while (!time_to_exit)
{
fgets(work_area, WORK_SIZE, stdin);
pthread_mutex_unlock(&work_mutex);
while (1)
{
pthread_mutex_lock(&work_mutex);
if (work_area[0] != '\0')
{
pthread_mutex_unlock(&work_mutex);
sleep(1);
}
else
{
break;
}
}
}
pthread_mutex_unlock(&work_mutex);
printf ("\nWaiting for thread to finish....\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0)
{
perror("Thread join failed !\n");
exit (EXIT_FAILURE);
}
printf ("Thread join\n");
pthread_mutex_destroy(&work_mutex);
exit (EXIT_SUCCESS);
}
void *thread_function(void *argc)
{
sleep(1);
pthread_mutex_lock(&work_mutex);
while (strncmp ("end", work_area, 3) != 0)
{
printf ("You input %d characters\n", strlen(work_area) - 1);
work_area[0] = '\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
while (work_area[0] == '\0')
{
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
}
}
time_to_exit = 1;
work_area[0] = '\0';
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
- 互斥锁的小例程
- SWT-JFace-Eclipse的例程小程序代码
- 各个层面的android小例程
- JAVA JDBC链接查询oracle 数据库的小例程
- Dsp28335 - ePWM - 50Hz小舵机的控制 - 代码例程
- 补充一个小问题:关于国嵌视频里面的进程创建例程的小错误
- java中简单小例程
- getline怎么用+小例程
- 以前在新浪写的DSP5509A汇编的学习小例程
- 小tip,如何使用别人的Android例程,安装卸载apk
- DM642学习点滴一:对例程VideoReverse的一点小思考
- 看8086汇编 书上的一个小作业 键盘中断例程编写
- C++例程与Java例程的对比
- 简单的Winsock例程
- 低频信号发生器的例程
- 使用wxPropertyGrid的例程
- IRP的完成例程
- StartIo例程的作用
- select
- SQL常用操作
- php中utf-8编码和GB2312编码下用正则表达式匹配汉字
- win7下安装Ubuntu系统 && 开发环境安装
- Java反射API(应用篇)
- 互斥锁的小例程
- 我们都一样
- struts2中上传文件不能超过2M的解决办法
- 求解字符串中最长对称字符串长度
- 手动加载驱动的方法
- poj 3122 水高精度二分 Pie
- 给虚拟机VMware7.0.1上的Ubuntu10.10安装VMware tools
- 7、8月份读书小结
- 三星推出1GHz ARM CORTEX-A8式应用处理器S5PC110及S5PV210