BogoToBogo
  • Home
  • About
  • Big Data
  • Machine Learning
  • AngularJS
  • Python
  • C++
  • go
  • DevOps
  • Kubernetes
  • Algorithms
  • More...
    • Qt 5
    • Linux
    • FFmpeg
    • Matlab
    • Django 1.8
    • Ruby On Rails
    • HTML5 & CSS

C++ Tutorial Quiz - Multithreading - 2020

cplusplus_icon.png




Bookmark and Share





bogotobogo.com site search:




mutex and condition variable

Q: Write a multi threaded C code with one thread printing all even numbers and the other all odd numbers. The output should always be in sequence ie. 0,1,2,3,4....etc.

The following program may not work:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

int MAX = 10;
int count = 0;

void *even(void *arg)
{
    printf("This is even thread()\n");
    while(count < MAX)
        if(count % 2 == 0)
            printf("%d ", count++);
    pthread_exit(0);
}

void *odd(void *arg)
{
    printf("This is odd thread()\n");
    while(count < MAX)
        if(count % 2 == 1)
            printf("%d ", count++);
    pthread_exit(0);
}

int main()
{
    pthread_t t1;
    pthread_t t2;

    pthread_create(&t1;, 0, &even;, NULL);
    pthread_create(&t2;, 0, &odd;, NULL);

    pthread_join(t1, 0);
    pthread_join(t2, 0);

    return  0;
}

Output:

1 0 2 3 4 5 6 7 9 8
or
1 0 2 4 3 5 6 7 8 9

There is no consistency in the output.


So, we need to modify the code like this:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

int MAX = 10;
int count = 0;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *even(void *arg)
{
    while(count < MAX) {
        pthread_mutex_lock(&mutex;);
        while(count % 2 != 0) {
            pthread_cond_wait(&cond;, &mutex;);
        }
        printf("%d ", count++);
        pthread_mutex_unlock(&mutex;);
        pthread_cond_signal(&cond;);
    }
    pthread_exit(0);
}

void *odd(void *arg)
{
    while(count < MAX) {
        pthread_mutex_lock(&mutex;);
        while(count % 2 != 1) {
            pthread_cond_wait(&cond;, &mutex;);
        }
        printf("%d ", count++);
        pthread_mutex_unlock(&mutex;);
        pthread_cond_signal(&cond;);
    }
    pthread_exit(0);
}

int main()
{
    pthread_t t1;
    pthread_t t2;

    pthread_mutex_init(&mutex;, 0);
    pthread_cond_init(&cond;, 0);

    pthread_create(&t1;, 0, &even;, NULL);
    pthread_create(&t2;, 0, &odd;, NULL);

    pthread_join(t1, 0);
    pthread_join(t2, 0);

    pthread_mutex_destroy(&mutex;);
    pthread_cond_destroy(&cond;);

    return  0;
}

The output looks like this:

0 1 2 3 4 5 6 7 8 9 10

The key components of the locking and condition checking are:

// for even() thread function

pthread_mutex_lock(&mutex;);       (lock before checking)

check 
   wait until count becomes even  (pthread_cond_wait(&cond;, &mutex;) 
                                   - wait for signal from another thread)
do something                      (print and count++)

pthread_mutex_unlock(&mutex;);     (release)
pthread_cond_signal(&cond;);       (signal to another thread)

When a thread calls pthread_cond_wait(&cond;, &mutex;), it releases the mutex and it waits till condition cond is signaled as complete and mutex is available.

Note that pthread_cond_signal(&cond;) does not have mutex as an argument while pthread_cond_wait(&cond;, &mutex;) has it.

pthread_cond_signal() does not unlock the mutex, and it can't. In fact, it does not need mutex. However, pthread_cond_wait() unlocks the mutex just before it sleeps, but then it reaquires the mutex (which may require waiting) when it is signalled, before it wakes up. So if the signalling thread holds the mutex (the usual case), the waiting thread will not proceed until the signalling thread also unlocks the mutex.




Bogotobogo's contents

To see more items, click left or right arrow.

I hope this site is informative and helpful.

Bogotobogo Image / Video Processing

Computer Vision & Machine Learning

with OpenCV, MATLAB, FFmpeg, and scikit-learn.

I hope this site is informative and helpful.

Bogotobogo's Video Streaming Technology

with FFmpeg, HLS, MPEG-DASH, H.265 (HEVC)

I hope this site is informative and helpful.






Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization

YouTubeMy YouTube channel

Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






Sponsor Open Source development activities and free contents for everyone.

Thank you.

- K Hong






C++ Tutorials

C++ Home

Algorithms & Data Structures in C++ ...

Application (UI) - using Windows Forms (Visual Studio 2013/2012)

auto_ptr

Binary Tree Example Code

Blackjack with Qt

Boost - shared_ptr, weak_ptr, mpl, lambda, etc.

Boost.Asio (Socket Programming - Asynchronous TCP/IP)...

Classes and Structs

Constructor

C++11(C++0x): rvalue references, move constructor, and lambda, etc.

C++ API Testing

C++ Keywords - const, volatile, etc.

Debugging Crash & Memory Leak

Design Patterns in C++ ...

Dynamic Cast Operator

Eclipse CDT / JNI (Java Native Interface) / MinGW

Embedded Systems Programming I - Introduction

Embedded Systems Programming II - gcc ARM Toolchain and Simple Code on Ubuntu and Fedora

Embedded Systems Programming III - Eclipse CDT Plugin for gcc ARM Toolchain

Exceptions

Friend Functions and Friend Classes

fstream: input & output

Function Overloading

Functors (Function Objects) I - Introduction

Functors (Function Objects) II - Converting function to functor

Functors (Function Objects) - General



Git and GitHub Express...

GTest (Google Unit Test) with Visual Studio 2012

Inheritance & Virtual Inheritance (multiple inheritance)

Libraries - Static, Shared (Dynamic)

Linked List Basics

Linked List Examples

make & CMake

make (gnu)

Memory Allocation

Multi-Threaded Programming - Terminology - Semaphore, Mutex, Priority Inversion etc.

Multi-Threaded Programming II - Native Thread for Win32 (A)

Multi-Threaded Programming II - Native Thread for Win32 (B)

Multi-Threaded Programming II - Native Thread for Win32 (C)

Multi-Threaded Programming II - C++ Thread for Win32

Multi-Threaded Programming III - C/C++ Class Thread for Pthreads

MultiThreading/Parallel Programming - IPC

Multi-Threaded Programming with C++11 Part A (start, join(), detach(), and ownership)

Multi-Threaded Programming with C++11 Part B (Sharing Data - mutex, and race conditions, and deadlock)

Multithread Debugging

Object Returning

Object Slicing and Virtual Table

OpenCV with C++

Operator Overloading I

Operator Overloading II - self assignment

Pass by Value vs. Pass by Reference

Pointers

Pointers II - void pointers & arrays

Pointers III - pointer to function & multi-dimensional arrays

Preprocessor - Macro

Private Inheritance

Python & C++ with SIP

(Pseudo)-random numbers in C++

References for Built-in Types

Socket - Server & Client

Socket - Server & Client 2

Socket - Server & Client 3

Socket - Server & Client with Qt (Asynchronous / Multithreading / ThreadPool etc.)

Stack Unwinding

Standard Template Library (STL) I - Vector & List

Standard Template Library (STL) II - Maps

Standard Template Library (STL) II - unordered_map

Standard Template Library (STL) II - Sets

Standard Template Library (STL) III - Iterators

Standard Template Library (STL) IV - Algorithms

Standard Template Library (STL) V - Function Objects

Static Variables and Static Class Members

String

String II - sstream etc.

Taste of Assembly

Templates

Template Specialization

Template Specialization - Traits

Template Implementation & Compiler (.h or .cpp?)

The this Pointer

Type Cast Operators

Upcasting and Downcasting

Virtual Destructor & boost::shared_ptr

Virtual Functions



Programming Questions and Solutions ↓

Strings and Arrays

Linked List

Recursion

Bit Manipulation

Small Programs (string, memory functions etc.)

Math & Probability

Multithreading

140 Questions by Google



Qt 5 EXPRESS...

Win32 DLL ...

Articles On C++

What's new in C++11...

C++11 Threads EXPRESS...

Go Tutorial

OpenCV...








Contact

BogoToBogo
contactus@bogotobogo.com

Follow Bogotobogo

About Us

contactus@bogotobogo.com

YouTubeMy YouTube channel
Pacific Ave, San Francisco, CA 94115

Pacific Ave, San Francisco, CA 94115

Copyright © 2024, bogotobogo
Design: Web Master