#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
void *thread_function (void *arg);
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) {
printf ("Mutex initialization failed");
exit (EXIT_FAILURE);
}
res = pthread_create (&a_thread, NULL, thread_function, NULL);
if (res != 0) {
printf ("Thread creation failed");
exit (EXIT_FAILURE);
}
pthread_mutex_lock (&work_mutex);
printf ("等待全部变量 time_to_exit 的变为 1\n");
while (!time_to_exit) {
printf ("还没改变,继续等待 3s ...\n");
sleep(3);
}
pthread_mutex_unlock (&work_mutex);
pthread_mutex_destroy (&work_mutex);
pthread_join (a_thread, &thread_result);
return (0);
}
void *thread_function (void *arg)
{
sleep(1);
pthread_mutex_lock (&work_mutex);
printf ("资源没有释放,无法打印此行信息\n");
time_to_exit = 1;
}
> ./pthread_lock
等待全部变量 time_to_exit 的变为 1
还没改变,继续等待 3s ...
还没改变,继续等待 3s ...
还没改变,继续等待 3s ...
... ... ...
欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) | Powered by Discuz! X3.2 |