Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <errno.h>
- //perror, strerror, вывести сообщение об ошибке
- using namespace std;
- pthread_mutex_t mtx;
- void *thread1(void *flag)
- {
- cout << "start thread 1\n";
- timespec timer;
- while (*(int*)flag != 0)
- {
- clock_gettime(CLOCK_REALTIME, &timer);
- timer.tv_sec += 2;
- if (pthread_mutex_timedlock(&mtx, &timer) == 0)
- {
- for (int i = 0; i < 2; i++)
- {
- cout << "1";
- fflush(stdout);
- sleep(1);
- }
- pthread_mutex_unlock(&mtx);
- sleep(2);
- }
- else
- {
- cout << "Mutex is unavailable" << "\n";
- fflush(stdout);
- if (*(int*)flag == 0) break;
- sleep(1);
- }
- }
- cout << "\nend thread 1\n";
- return 0;
- }
- void *thread2(void *flag)
- {
- cout << "\nstart thread 2\n";
- timespec timer;
- while (*(int*)flag != 0)
- {
- clock_gettime(CLOCK_REALTIME, &timer);
- timer.tv_sec += 3;
- if (pthread_mutex_timedlock(&mtx, &timer) == 0)
- {
- for (int i = 0; i < 2; i++)
- {
- cout << "2";
- fflush(stdout);
- sleep(1);
- }
- pthread_mutex_unlock(&mtx);
- sleep(2);
- }
- else
- {
- cout << "Mutex is unavailable" << "\n";
- fflush(stdout);
- if (*(int*)flag == 0) break;
- sleep(1);
- }
- }
- cout << "\nend thread 2\n";
- return 0;
- }
- int main()
- {
- int fl1, fl2;
- void *retval[2];
- pthread_t thr1, thr2;
- pthread_mutex_init(&mtx, NULL);
- fl1 = fl2 = 1;
- pthread_create(&thr1, NULL, &thread1, &fl1);
- pthread_create(&thr2, NULL, &thread2, &fl2);
- getchar();
- fl1 = fl2 = 0;
- cout << "\n";
- pthread_join(thr1, &retval[0]);
- pthread_join(thr2, &retval[1]);
- pthread_mutex_destroy(&mtx);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement