Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void * thread2(void *args) {
- while (1) {
- pthread_mutex_lock(&lock);
- if (counter <= MAX_COUNTER_LIMIT) {
- sum = sum + counter;
- counter++;
- }
- else {
- pthread_mutex_unlock(&lock);
- break;
- }
- pthread_mutex_unlock(&lock);
- }
- }
- /* Similar to thread1 function */
- void * thread3(void *args) {
- while (1) {
- pthread_mutex_lock(&lock);
- if (counter <= MAX_COUNTER_LIMIT) {
- sum = sum + counter;
- counter++;
- }
- else {
- pthread_mutex_unlock(&lock);
- break;
- }
- pthread_mutex_unlock(&lock);
- }
- }
- /* Similar to thread1 function */
- void * thread4(void *args) {
- while (1) {
- pthread_mutex_lock(&lock);
- if (counter <= MAX_COUNTER_LIMIT) {
- sum = sum + counter;
- counter++;
- }
- else {
- pthread_mutex_unlock(&lock);
- break;
- }
- pthread_mutex_unlock(&lock);
- }
- }
- int main() {
- /* Declaring 4 thread variables */
- pthread_t t1, t2, t3, t4;
- /* Initializing mutex lock */
- if (pthread_mutex_init(&lock, NULL) != 0) {
- cout << "Mutex init failed\n";
- return 1;
- }
- /* Creating thread1 which run thread1() function */
- pthread_create(&t1, NULL, thread1, NULL);
- /* Creating thread2 which run thread2() function */
- pthread_create(&t2, NULL, thread2, NULL);
- /* Creating thread3 which run thread3() function */
- pthread_create(&t3, NULL, thread3, NULL);
- /* Creating thread4 which run thread4() function */
- pthread_create(&t4, NULL, thread4, NULL);
- /* Joining all threads to main thread, so that it waits until 4 threads complete
- * their execution */
- pthread_join(t1, NULL);
- pthread_join(t2, NULL);
- pthread_join(t3, NULL);
- pthread_join(t4, NULL);
- /* destroying mutex lock */
- pthread_mutex_destroy(&lock);
- /* Printing the final counter value and and Sum */
- cout << ("Final Sum added by 4 threads: %lld\n", sum);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement