Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <iostream>
- using namespace std;
- void* threadOne(void* flag){
- void* counter = malloc(sizeof(int));
- *(int*)counter = 0;
- puts("threadOne started");
- while (*reinterpret_cast<bool*>(flag)) {
- puts("1");
- (*(int*)counter)++;
- sleep(1);
- }
- puts("threadOne finished");
- pthread_exit(counter);
- }
- void* threadTwo(void* flag){
- void* counter = malloc(sizeof(int));
- *(int*)counter = 0;
- puts("threadTwo started");
- while (*reinterpret_cast<bool*>(flag)) {
- puts("2");
- (*(int*)counter)++;
- sleep(1);
- }
- puts("threadTwo finished");
- pthread_exit(counter);
- }
- int main(int argc, char** argv) {
- pthread_t thread1;
- pthread_t thread2;
- bool flag1 = true;
- bool flag2 = true;
- if(pthread_create(&thread1, NULL, threadOne, (void*)&flag1)){
- return EXIT_FAILURE;
- }
- if(pthread_create(&thread2, NULL, threadTwo, (void*)&flag2)){
- return EXIT_FAILURE;
- }
- getchar();
- flag1 = false;
- flag2 = false;
- int *firstCounter = nullptr;
- int *secondCounter = nullptr;
- if(pthread_join(thread1, (void**)&firstCounter)){
- return EXIT_FAILURE;
- }
- if(pthread_join(thread2, (void**)&secondCounter)){
- return EXIT_FAILURE;
- }
- cout<<*firstCounter<<endl;
- cout<<*secondCounter<<endl;
- free(firstCounter);
- free(secondCounter);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement