使用互斥量实现线程间同步
2013-08-10 12:31
295 查看
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <semaphore.h> #define SIZE 1024 char buffer[SIZE]; void *thread_function(void *arg); pthread_mutex_t mutex; int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&mutex, NULL); if (res != 0) { perror("Mutex init failed!"); exit(EXIT_FAILURE); } res = pthread_create(&a_thread, NULL, thread_function, NULL); if (res != 0) { perror("Thread create failed!"); exit(EXIT_FAILURE); } printf("Input some text. Enter 'end' to finish/n"); while (1) { pthread_mutex_lock(&mutex); scanf("%s", buffer); pthread_mutex_unlock(&mutex); if (strncmp("end", buffer, 3) == 0) break; sleep(1); } res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed!"); exit(EXIT_FAILURE); } printf("Thread joined/n"); pthread_mutex_destroy(&mutex); exit(EXIT_SUCCESS); } void *thread_function(void *arg) { sleep(1); while (1) { pthread_mutex_lock(&mutex); printf("You input %d characters/n", strlen(buffer)); pthread_mutex_unlock(&mutex); if (strncmp("end", buffer, 3) == 0) break; sleep(1); } }
相关文章推荐
- Java并发编程中级篇(四):使用CyclicBarrier实现并发线程在集合点同步
- Linux多线程——使用互斥量同步线程
- Linux多线程——使用互斥量同步线程
- 2.使用synchronized关键字实现多线程的同步和互斥(不同线程同时读写同一数据)
- Linux多线程——使用互斥量同步线程
- Linux多线程——使用互斥量同步线程
- 使用信号量实现线程间同步
- 多线程---使用ManualResetEvent来控制线程间的同步(实现了消费者和生产者模式)
- 线程间的同步----利用互斥量来实现
- Linux多线程——使用互斥量同步线程
- Linux多线程——使用互斥量同步线程
- Java 有几程方法可以实现一个线程?用什么关键字修饰同步?stop()和suspend()为什么不推荐使用?
- QT之使用QReadWriteLocker互斥量同步线程小例子
- java基础问题---java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用
- 使用事件对象实现线程间的同步
- C#使用互斥量(Mutex)实现多进程并发操作时多进程间线程同步操作(进程同步)的简单示例代码及使用方法
- Visual C++利用互斥量同步线程实现文件读取进度条
- Linux多线程——使用互斥量同步线程
- java中有几种方法可以实现一个线程?用什么关键字修饰同步方法? stop()和suspend()方法为何不推荐使用
- Linux多线程——使用互斥量同步线程