C++ Tutorial - Multi-Threaded Programming - C++ Class Thread For Pthreads - 2012

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012

1/15 .bogotobogo.com/cplusplus/multithreaded3.php
bogotobogo
Home|AboutUs|Products|OurServices|ContactUs
Gif|JavaApplet|SVG|iPhone/iPad|Android|HTML5|Algorithms|News|C++|Linux|Java|PHP|
DesignPatterns|Python|C#|Forums|VB|VideoStreamingetc.
Search

C++Tutorial
MultiThreadedProgrammingIII
C++ClassThreadforPthreads2012
l
FullListofC++Tutorials
C++ Home
String
Constructor
Operator Overloading
Virtual Functions
Dynamic Cast Operator
Type Cast Operators
Class auto_ptr
References for Built-in Types
Pass by Value vs. Pass by Reference
Bogotobogo
contact@bogotobogo.com
Home|Sitemap|ContactUs
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
2/15 .bogotobogo.com/cplusplus/multithreaded3.php
Memory Allocation
Friend Functions and Friend Classes
Functors (Function Objects)
Static Variables and Static Class Members
Exceptions
Stack Unwinding
Pointers
Pointers ll - void pointers & arrays
Pointers lll - pointer to function & multi-dimensional arrays
Taste of Assembly
Small Programs
Linked List Examples
Binary Tree Example Code
Templates
Standard Template Library (STL) l
Standard Template Library (STL) ll - Maps
Standard Template Library (STL) lll - lterators
Standard Template Library (STL) lV - Algorithms
Object Slicing and Virtual Table
The this Pointer
Stack Unwinding
Upcasting and Downcasting
Object Returning
Private lnheritance
Preprocessor - Macro
C++_Keywords
fstream: input & output
Multi-Threaded Programming - Terminology
Multi-Threaded Programming ll - Native Thread for Win32 (A)
Multi-Threaded Programming ll - Native Thread for Win32 (B)
Multi-Threaded Programming ll - Native Thread for Win32 (C)
Multi-Threaded Programming ll - C++ Thread for Win32
Multi-Threaded Programming lll - C++ Class Thread for Pthreads
Multithread Debugging
Socket - Server & Client
Embedded Systems Programming
Boost
make
Libraries
C++ APl Testing
Design Patterns in C++
Algorithms in C++
Programming Questions and Solutions
Strings and Arrays
Linked List
Recursion
Bit Manipulation
l40 Google lnterview Questions
Blackjack with Qt

13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
3/15 .bogotobogo.com/cplusplus/multithreaded3.php
MultiThreadedProgrammingIII:Pthread
WhatarePthreads?
POSIXThreads, or Pthreads, is a POSlX standard for threads. The standard, POSlX.lc, Threads extensions (lEEE Std
l003.lc-l995), defines an APl for creating and manipulating threads.
lmplementations of the APl are available on many Unix-like POSlX systems such as FreeBSD, NetBSD, GNU/Linux,
Mac OS X and Solaris, but Microsoft Windows implementations also exist. For example, the pthreads-w32 is
available and supports a subset of the Pthread APl for the Windows 32-bit platform.
The POSlX standard has continued to evolve and undergo revisions, including the Pthreads specification. The latest
version is known as lEEE Std l003.l, 2004 Edition.
Pthreads are defined as a set of C language programming types and procedure calls, implemented with a pthread.h
header/include file and a thread library - though this library may be part of another library, such as libc, in some
implementations.

ThePthreadAPI
Pthreads APl can be grouped into four:
Threadmanagement:
Routines that work directly on threads - creating, detaching, joining, etc. They also include functions to set/query thread
attributes such as joinable, scheduling etc.
Mutexes:
Routines that deal with synchronization, called a "mutex", which is an abbreviation for "mutual exclusion". Mutex
functions provide for creating, destroying, locking and unlocking mutexes. These are supplemented by mutex attribute
functions that set or modify attributes associated with mutexes.
Conditionvariables:
Routines that address communications between threads that share a mutex. Based upon programmer specified
conditions. This group includes functions to create, destroy, wait and signal based upon specified variable values.
Functions to set/query condition variable attributes are also included.
Synchronization:
Routines that manage read/write locks and barriers.
CoolYoutubeVideo!
Check Out This Awesome Youtube Video! Have You
Ever Seen This Before?
YouTube.com
BestJobInTheWorld!
Ever Wonder How America's Trains Are Built? Watch
And Find Out!
Youtube.com
CoolestJobEver!
Watch How America's Trains Are Designed!
Youtube.com
CoolYoutubeVideo!
Check Out This Behind The Scenes Look! Don't Miss
This Video!
Youtube.com
YourAdHere
CreatingThreads
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
4/15 .bogotobogo.com/cplusplus/multithreaded3.php
Our main() program is a single, default thread. All other threads must be explicitly created by the programmer.
pthread_create creates a new thread and makes it executable. This routine can be called any number of times from
anywhere within our code.
pthread_create(pthread_t*thread,pthread_attr_t*attr,void*(*start_routine)(void*),void*arg)arguments:
thread:
An opaque, unique identifier for the new thread returned by the subroutine. This is a pointer to pthread_t. When
a thread is created, an identifier is written to the memory location to which this variable points. This identifier
enables us to refer to the thread.
attr:
An opaque attribute object that may be used to set thread attributes. You can specify a thread attributes object,
or NULL for the default values.
start_routine:
The routine that the thread will execute once it is created.
void*(*start_routine)(void*)

We should pass the address of a function taking a pointer to void as a parameter and the function will return a
pointer to void. So, we can pass any type of single argument and return a pointer to any type.
While using fork() causes execution to continue in the same location with a different return code, using a new
thread explicitly provides a pointer to a function where the new thread should start executing.
arg:
A single argument that may be passed to start_routine. lt must be passed by reference as a pointer cast of type
void. NULL may be used if no argument is to be passed.
The maximum number of threads that may be created by a process is implementation dependent.
Once created, threads are peers, and may create other threads. There is no implied hierarchy or dependency between
threads.
AttributesofThreads
By default, a thread is created with certain attributes. Some of these attributes can be changed by the programmer via
the thread attribute object.
pthread_attr_init() and pthread_attr_destroy() are used to initialize/destroy the thread attribute object.
Other routines are then used to query/set specific attributes in the thread attribute object.
TerminatingThreads
There are several ways in which a Pthread may be terminated:
The thread returns from its starting routine (the main routine for the initial thread).
The thread makes a call to the pthread_exit subroutine.
The thread is canceled by another thread via the pthread_cancel routine
The entire process is terminated due to a call to either the exec or exit subroutines.
`
pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit() routine is called after a thread has
completed its work and is no longer required to exist. lf main() finishes before the threads it has created, and exits with
pthread_exit(), the other threads will continue to execute. Otherwise, they will be automatically terminated when main()
finishes.
The programmer may optionally specify a termination status, which is stored as a void pointer for any thread that may
join the calling thread.
Cleanup: the pthread_exit() routine does not close files any files opened inside the thread will remain open after the
thread is terminated.
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
5/15 .bogotobogo.com/cplusplus/multithreaded3.php
Join
intpthread_join(pthread_tth,void**thread_return)
The first parameter is the thread for which to wait, the identified that pthread_create filled in for us. The second
argument is a pointer to a pointer that itself points to the return value from the thread. This function returns zero for
success and an error code on failure.
When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created
as joinable can be joined. lf a thread is created as detached, it can never be joined.
The final draft of the POSlX standard specifies that threads should be created as joinable.
To explicitly create a thread as joinable or detached, the attr argument in the pthread_create() routine is used. The
typical 4 step process is:
Declare a pthread attribute variable of the pthread_attr_t data type.
lnitialize the attribute variable with pthread_attr_init().
Set the attribute detached status with pthread_attr_setdetachstate()
When done, free library resources used by the attribute with pthread_attr_destroy()
Detaching
There are cases we have to resynchronize our threads using pthread_join() before allowing the program to exit. We need to
do this if we want to allow one thread to return data to the thread that created it. However, sometimes we neither need the
second thread to return information to the main thread nor want the main thread to wait for it.
Suppose we create a second thread to spool a backup copy of a data file that is being edited while the main thread continues
to service the user. When the backup has finished, the second thread can just terminate, and there is no need for it to join the
main thread.
We can create threads that have this behavior. They are called detachedthreads, and we can create them by modifying the
thread attributes or by calling pthread_detach().
The pthread_detach() routine can be used to explicitly detach a thread even though it was created as joinable.
There is no converse routine.
TheSimplestPthreadExample
The example below is probably one of the simplest Pthread example. The newly created thread is sharing global variable with
the original thread. lt modifies the variable.
//thread1.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
void*thread_fnc(void*arg)
charthread_msg[]="HelloThread!"
intmain()
{
intret
pthread_tmy_thread
void*ret_join
ret=pthread_create(&my_thread,NULL,thread_fnc,(void*)thread_msg)
if(ret!=0){
perror("pthread_createfailed\n")
exit(EXIT_FAILURE)

printf("Waitingforthreadtofinish...\n")
ret=pthread_join(my_thread,&ret_join)
if(ret!=0){
perror("pthread_joinfailed")
exit(EXIT_FAILURE)
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
6/15 .bogotobogo.com/cplusplus/multithreaded3.php

printf("Threadjoined,itreturned%s\n",(char*)ret_join)
printf("Newthreadmessage:%s\n",thread_msg)
exit(EXIT_SUCCESS)

void*thread_fnc(void*arg)
{
printf("Thisisthread_fnc(),argis%s\n",(char*)arg)
strcpy(thread_msg,"Bye!")
pthread_exit("Bye")

And the make file:


thread1:thread1.o
gccD_REENTRANTothread1thread1.olpthread
thread1.o:thread1.c
gcccthread1.c
clean:
rmf*.othread1
Output from the run:
$./thread1
Waitingforthreadtofinish...
Thisisthread_fnc(),argisHelloThread!
Threadjoined,itreturnedBye
Newthreadmessage:Bye!
We declare a prototype for the function that the thread calls when we create it:
void*thread_fnc(void*arg)
lt takes a pointer to void as its argument and returns a pointer to void, which is required by pthreadcreate().
ln main(), we call pthreadcreate() to start running our new thread:
ret=pthread_create(&my_thread,NULL,thread_fnc,(void*)thread_msg)
We are passing the address of a pthread_t object that we can use to refer to the thread later. For the thread attribute, we
pass NULL since we do not want to modify the default values.
lf the call succeeds, two threads will be running. The original thread (main) continues and execute the code after pthread
create(), and a new thread starts executing in the threadfnc().
The original thread checks if the new thread has started, and then calls pthread_join():
ret=pthread_join(my_thread,&ret_join)
We pass the identifier of the thread that we are waiting to join and a pointer to a result. This function will wait until the other
thread terminates before it returns. Then, it prints the return value from the thread.
The new thread starts executing at the start of thread_fnc(), which updates global variable, returning a string to the main
thread.
SynchronizationPthreadExampleSemaphores
ln this example, we will use a binarysemaphore which takes 0 or l. There is a more general type of semaphore, a counting
semaphore which takes a wider range of values. Semaphores are used to protect a section of code so that only one thread
can run it at the given time. To do this kind of task, a binary semaphore is needed. However, if we want to permit a limited
number of threads to execute a piece of code, we may need a counting semaphore.
There are 4 basic semaphore functions, but unlike most of the function which start with pthread_, semaphore functions start
with sem_.
A semaphore is created with the sem_init function, and it is declared in semaphore.h:
intsem_init(sem_t*sem,intpshared,unsignedintval)
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
7/15 .bogotobogo.com/cplusplus/multithreaded3.php
lt initializes a semaphore object pointed by sem, sets its sharing option, and gives it an initial integer value. The
pshared parameter controls the type of semaphore. lf the value of pshared is 0, the semaphore is local to the current
process. Otherwise, the semaphore may be shared between processes.
intsem_post(sem_t*sem)
This function atomically increases the value of the semaphore by 1.
intsem_wait(sem_t*sem)
This function atomically decreases the value of the semaphore by 1, but always waits until the semaphore has a
nonzero count first. So, if we call sem_wait on a semaphore with a value of 2, the thread will continue executing but the
semaphore will be decreased to 1. lf we call it on a semaphore with a value of 0, the function will wait until some other
thread has incremented the value so that it is no longer 0. lf two thread are both waiting in sem_wait for the same
semaphore to be nonzero and it is incremented once by a third process, only one of the two waiting process will get to
decrement the semaphore and continue while the other will remain waiting.
intsem_destroy(sem_t*sem)
This function tidies up the semaphore when we have finished with it. This function takes a pointer to a semaphore and
tidies up any resources that it may have. lf we attempt to destroy a semaphore for which some thread is waiting, we get
an error.
//sem.c
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include<semaphore.h>
void*thread_fnc(void*arg)
/*semaphoresaredeclaredglobalsotheycanbeaccessed
inmain()andinthreadroutine*/
sem_tmy_semaphore
charmy_string[100]/*sharedvariable*/
intmain()
{
intret
intvalue
pthread_tmy_thread
void*ret_join
/*initializemutexto1binarysemaphore*/
/*secondparam=0semaphoreislocal*/
ret=sem_init(&my_semaphore,0,0)
sem_getvalue(&my_semaphore,&value)
printf("Theinitialvalueofthesemaphoreis%d\n",value)
if(ret!=0){
perror("semaphoreinitfailed\n")
exit(EXIT_FAILURE)

ret=pthread_create(&my_thread,NULL,thread_fnc,NULL)
if(ret!=0){
perror("pthread_createfailed\n")
exit(EXIT_FAILURE)

printf("Typeinsomecharacters.Enter'quit'tofinish\n")
while(strncmp("quit",my_string,4)!=0){
fgets(my_string,100,stdin)
sem_post(&my_semaphore)
sem_getvalue(&my_semaphore,&value)
printf("Thevalueofthesemaphoreaftersem_post()is%d\n",value)

13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
8/15 .bogotobogo.com/cplusplus/multithreaded3.php
printf("Waitingforthreadtofinish...\n")
ret=pthread_join(my_thread,&ret_join)
if(ret!=0){
perror("pthread_joinfailed")
exit(EXIT_FAILURE)

printf("Threadjoined,itreturned%s\n",(char*)ret_join)
sem_destroy(&my_semaphore)
exit(EXIT_SUCCESS)

void*thread_fnc(void*arg)
{
intval
printf("Thisisthread_fnc(),waitingfornonzerocount...\n")
sem_getvalue(&my_semaphore,&val)
printf("Thevalueofthesemaphoreinthread_fnc()is%d\n",val)
sem_wait(&my_semaphore)
sem_getvalue(&my_semaphore,&val)
printf("Thevalueofthesemaphoreaftersem_wait()inthread_fnc()is%d\n",val)
while(strncmp("quit",my_string,4)!=0){
printf("Youtypedin%dcharacters\n",strlen(my_string)1)
sem_getvalue(&my_semaphore,&val)
printf("Thevalueofthesemaphorebeforesem_wait()inthread_fnc()is%d\n",val)
sem_wait(&my_semaphore)
sem_getvalue(&my_semaphore,&val)
printf("Thevalueofthesemaphoreaftersem_wait()inthread_fnc()is%d\n",val)

pthread_exit(NULL)

Output is:
$./sem
Theinitialvalueofthesemaphoreis0
Typeinsomecharacters.Enter'quit'tofinish
Thisisthread_fnc(),waitingfornonzerocount...
Thevalueofthesemaphoreinthread_fnc()is0
1234
Thevalueofthesemaphoreaftersem_post()is1
Thevalueofthesemaphoreaftersem_wait()inthread_fnc()is0
Youtypedin4characters
Thevalueofthesemaphorebeforesem_wait()inthread_fnc()is0
98
Thevalueofthesemaphoreaftersem_post()is1
Thevalueofthesemaphoreaftersem_wait()inthread_fnc()is0
Youtypedin2characters
Thevalueofthesemaphorebeforesem_wait()inthread_fnc()is0
quit
Thevalueofthesemaphoreaftersem_post()is1
Waitingforthreadtofinish...
Thevalueofthesemaphoreaftersem_wait()inthread_fnc()is0
Threadjoined,itreturned(null)
ln main(), after creating a new thread, we read in text, and put it into my_string which is global, and the incremented the
semaphore with sem_post():
while(strncmp("quit",my_string,4)!=0){
fgets(my_string,100,stdin)
sem_post(&my_semaphore)

ln the new thread, we wait for the semaphore and then count the characters from the input:
sem_wait(&my_semaphore)
while(strncmp("quit",my_string,4)!=0){
printf("Youtypedin%dcharacters\n",strlen(my_string)1)
sem_wait(&my_semaphore)

13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
9/15 .bogotobogo.com/cplusplus/multithreaded3.php
While the semaphore is set, we are waiting for keyboard input. When we have input, we release the semaphore allowing the
second thread to count the characters before the first thread reads the keyboard input again.
Note that both threads share the same my_string array.
SynchronizationPthreadExampleMutexes
The other way of synchronizing access is with mutexes, which act by allowing us to lock an object so that only one thread can
access to it. To control access, we lock a mutex before entering the section of the code, and then unlock it when we have
finished.
int pthread_mutex_init(pthread_mutex_t m_mutex, const pthread_mutexattr_t mutexattr)
intpthread_mutex_lock(pthread_mutex_t*m_mutex)
intpthread_mutex_unlock(pthread_mutex_t*m_mutex)
intpthread_mutex_destroy(pthread_mutex_t*m_mutex)
As with semaphore, all of the functions take a pointer to a previously declared object, in this case, pthread_mutex_t. The
extra attribute parameter pthread_mutex_init allows us to provide attributes for the mutex, which controls its behavior.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<pthread.h>
#include<semaphore.h>
void*thread_fnc(void*arg)
pthread_mutex_tmy_mutex
charmy_string[100]/*sharedvariable*/
inttime_to_exit=0
intmain()
{
intret
pthread_tmy_thread
void*ret_join
ret=pthread_mutex_init(&my_mutex,NULL)
if(ret!=0){
perror("mutexinitfailed\n")
exit(EXIT_FAILURE)

ret=pthread_create(&my_thread,NULL,thread_fnc,NULL)
if(ret!=0){
perror("pthread_createfailed\n")
exit(EXIT_FAILURE)

pthread_mutex_lock(&my_mutex)
printf("Typeinsomecharacters.Enter'quit'tofinish\n")
while(!time_to_exit){
fgets(my_string,100,stdin)
pthread_mutex_unlock(&my_mutex)
while(1){
if(my_string[0]!='\0'){
pthread_mutex_unlock(&my_mutex)
sleep(1)

else
break

pthread_mutex_unlock(&my_mutex)
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
10/15 .bogotobogo.com/cplusplus/multithreaded3.php
printf("Waitingforthreadtofinish...\n")
ret=pthread_join(my_thread,&ret_join)
if(ret!=0){
perror("pthread_joinfailed")
exit(EXIT_FAILURE)

printf("Threadjoined\n")
pthread_mutex_destroy(&my_mutex)
exit(EXIT_SUCCESS)

void*thread_fnc(void*arg)
{
sleep(1)
pthread_mutex_lock(&my_mutex)
while(strncmp("quit",my_string,4)!=0){
printf("Youtypedin%dcharacters\n",strlen(my_string)1)
my_string[0]='\0'
pthread_mutex_unlock(&my_mutex)
sleep(1)
pthread_mutex_lock(&my_mutex)
if(my_string[0]!='\0'){
pthread_mutex_unlock(&my_mutex)
sleep(1)
pthread_mutex_lock(&my_mutex)

time_to_exit=1
my_string[0]='\0'
pthread_mutex_unlock(&my_mutex)
pthread_exit(NULL)

Let's look at the thread function. The new thread tries to lock the mutex. lf it's already locked, the call will block until it is
released. Once we have access, we check to see if we are being requested to exit. lf we are requested to exit, then simply set
time_to_exit, zap the first character of the my_string, and exit.
lf we do not want to exit, count the characters and then zap the first character to a null. We use the first character being null as
a way of telling the reader program that we have finished the counting. We then unlock the mutex and wait for the main thread
to run. We attempt to lock the mutex and, when we succeed, check if the main thread has given us any more work to do. lf
that's not the case, we unlock the mutex and wait more. lf we have work to do, we count the characters and loop through
again.
Here is the output:
$./mutex
Typeinsomecharacters.Enter'quit'tofinish
12345
Youtypedin5characters
Youtypedin1characters
999
Youtypedin3characters
Youtypedin1characters
Youtypedin1characters
quit
Waitingforthreadtofinish...
Threadjoined
C++ClassesforPthreads
We'll make C++ classes Runnable and Thread for Pthreads. The interfaces are almost identical to the Win32 version of the
previous chapter. The only difference is the Thread class constructor has a parameter indicating whether or not the thread is
to be created in a detached state. The default is set to undetached
ln this code, we added communications between the threads. We selected shared memory to demonstrate the
communications between the threads. Because threads in the same program can reference global variables or call methods
on a shared object, threads in different processes can access the same kernel objects by calling kernel routines.
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
11/15 .bogotobogo.com/cplusplus/multithreaded3.php
#include<iostream>
#include<pthread.h>
#include<cassert>
#include<error.h>
usingnamespacestd
classRunnable{
public:
virtualvoid*run()=0
virtualRunnable()=0

//Purevirtualdestructor:functionbodyrequired
Runnable::Runnable(){
classThread{
public:
Thread(auto_ptr<Runnable>run,boolisDetached=false)
Thread(boolisDetached=false)
virtualThread()
voidstart()
void*join()
private:
//threadID
pthread_tPthreadThreadID
//trueifthreadcreatedindetachedstate
booldetached
pthread_attr_tthreadAttribute
//runnableobjectwillbedeletedautomatically
auto_ptr<Runnable>runnable
Thread(constThread&)
constThread&operator=(constThread&)
//calledwhenrun()completes
voidsetCompleted()
//storesreturnvaluefromrun()
void*result
virtualvoid*run(){
staticvoid*startThreadRunnable(void*pVoid)
staticvoid*startThread(void*pVoid)
voidprintError(char*msg,intstatus,char*fileName,intlineNumber)

Thread::Thread(auto_ptr<Runnable>r,boolisDetached):
runnable(r),detached(isDetached){
if(!runnable.get()){
cout<<"Thread::Thread(auto_ptr<Runnable>r,boolisDetached)"\
"failedat"<<""<<__FILE__<<":"<<__LINE__<<""<<
"runnableisNULL"<<endl
exit(1)

Thread::Thread(boolisDetached):runnable(NULL),detached(isDetached){
void*Thread::startThreadRunnable(void*pVoid){
//threadstartfunctionwhenaRunnableisinvolved
Thread*runnableThread=static_cast<Thread*>(pVoid)
assert(runnableThread)
runnableThread>result=runnableThread>runnable>run()
runnableThread>setCompleted()
returnrunnableThread>result

void*Thread::startThread(void*pVoid){
//threadstartfunctionwhennoRunnableisinvolved
Thread*aThread=static_cast<Thread*>(pVoid)
assert(aThread)
aThread>result=aThread>run()
aThread>setCompleted()
returnaThread>result
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
12/15 .bogotobogo.com/cplusplus/multithreaded3.php

Thread::Thread(){
voidThread::start(){
//initializeattributeobject
intstatus=pthread_attr_init(&threadAttribute)
if(status){
printError("pthread_attr_initfailedat",status,
__FILE__,__LINE__)
exit(status)

//settheschedulingscopeattribute
status=pthread_attr_setscope(&threadAttribute,
PTHREAD_SCOPE_SYSTEM)
if(status){
printError("pthread_attr_setscopefailedat",status,
__FILE__,__LINE__)
exit(status)

if(!detached){
if(!runnable.get()){
status=pthread_create(&PthreadThreadID,&threadAttribute,
Thread::startThread,(void*)this)
if(status){
printError("pthread_createfailedat",status,
__FILE__,__LINE__)
exit(status)


else{
status=pthread_create(&PthreadThreadID,&threadAttribute,
Thread::startThreadRunnable,(void*)this)
if(status){
printError("pthread_createfailedat",status,
__FILE__,__LINE__)
exit(status)



else{
//setthedetachstateattributetodetached
status=pthread_attr_setdetachstate(&threadAttribute,
PTHREAD_CREATE_DETACHED)
if(status){
printError("pthread_attr_setdetachstatefailedat",status,
__FILE__,__LINE__)
exit(status)

if(!runnable.get()){
status=pthread_create(&PthreadThreadID,&threadAttribute,
Thread::startThread,(void*)this)
if(status){
printError("pthread_createfailedat",status,
__FILE__,__LINE__)
exit(status)


else{
status=pthread_create(&PthreadThreadID,&threadAttribute,
Thread::startThreadRunnable,(void*)this)
if(status){
printError("pthread_createfailedat",status,
__FILE__,__LINE__)
exit(status)



13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
13/15 .bogotobogo.com/cplusplus/multithreaded3.php
status=pthread_attr_destroy(&threadAttribute)
if(status){
printError("pthread_attr_destroyfailedat",status,
__FILE__,__LINE__)
exit(status)

void*Thread::join(){
//AthreadcallingT.join()waitsuntilthreadTcompletes.
intstatus=pthread_join(PthreadThreadID,NULL)
//resultwasalreadysavedbythreadstartfunction
if(status){
printError("pthread_joinfailedat",status,
__FILE__,__LINE__)
exit(status)

returnresult

voidThread::setCompleted(){
//completionhandledbypthread_join()

voidThread::printError(char*msg,intstatus,char*fileName,intlineNumber){
cout<<msg<<""<<fileName<<":"<<lineNumber<<
""<<strerror(status)<<endl

//sharedvariable
ints=0
classcommunicatingThread:publicThread{
public:
communicatingThread(intID):myID(ID){
virtualvoid*run()
private:
intmyID

void*communicatingThread::run(){
cout<<"Thread"<<myID<<"isrunning!"<<endl
//incrementsbymilliontimes
for(inti=0i<1000000i++)s+=1
return0

intmain(){
auto_ptr<communicatingThread>thread1(newcommunicatingThread(1))
auto_ptr<communicatingThread>thread2(newcommunicatingThread(2))
thread1>start()
thread2>start()
thread1>join()
thread2>join()
cout<<"s="<<s<<endl
return0

l. ln main(), we created two communicatingTthreads.


auto_ptr<communicatingThread>thread1(newcommunicatingThread(1))
auto_ptr<communicatingThread>thread2(newcommunicatingThread(2))
2. Each communicatingThread increments the global shared variable s one million times.
AdsBClicksor
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
14/15 .bogotobogo.com/cplusplus/multithreaded3.php
for(inti=0i<1000000i++)s+=1
3. The main thread uses join() to wait for the communicatingThread to complete.
thread1>join()
thread2>join()
The results from the run should be 2,000,000, most of the runs.
Note
We may get a message saying "undefinedreferencetopthread_join", when we compile/link with g++code.cpp.
Then, try g++code.cpplpthread.

FullListofC++Tutorials
C++ Home
String
Constructor
Operator Overloading
Virtual Functions
Dynamic Cast Operator
Type Cast Operators
Class auto_ptr
References for Built-in Types
Pass by Value vs. Pass by Reference
Memory Allocation
Friend Functions and Friend Classes
Functors (Function Objects)
Static Variables and Static Class Members
Exceptions
Stack Unwinding
Pointers
Pointers ll - void pointers & arrays
Pointers lll - pointer to function & multi-dimensional arrays
Taste of Assembly
Small Programs
Linked List Examples
Binary Tree Example Code
Templates
Standard Template Library (STL) l
Standard Template Library (STL) ll - Maps
Standard Template Library (STL) lll - lterators
Standard Template Library (STL) lV - Algorithms
Object Slicing and Virtual Table
The this Pointer
13/04/12 C++ Tutorial: Multi-Threaded Programming - C++ Class Thread for Pthreads - 2012
15/15 .bogotobogo.com/cplusplus/multithreaded3.php
Stack Unwinding
Upcasting and Downcasting
Object Returning
Private lnheritance
Preprocessor - Macro
C++_Keywords
fstream: input & output
Multi-Threaded Programming - Terminology
Multi-Threaded Programming ll - Native Thread for Win32 (A)
Multi-Threaded Programming ll - Native Thread for Win32 (B)
Multi-Threaded Programming ll - Native Thread for Win32 (C)
Multi-Threaded Programming ll - C++ Thread for Win32
Multi-Threaded Programming lll - C++ Class Thread for Pthreads
Multithread Debugging
Socket - Server & Client
Embedded Systems Programming
Boost
make
Libraries
C++ APl Testing
Design Patterns in C++
Algorithms in C++
Programming Questions and Solutions
Strings and Arrays
Linked List
Recursion
Bit Manipulation
l40 Google lnterview Questions
Blackjack with Qt
Home|AboutUs|products|OurServices|ContactUs|Bogotobogo2012|Bogotobogo

You might also like