C++ MULTITHREADING. An opaque, unique identifier for the new thread returned by the subroutine.

Similar documents
Threads Scheduling on Linux Operating Systems

Writing a C-based Client/Server

THREADS, LIKE PROCESSES, ARE A MECHANISM TO ALLOW A PROGRAM to do more than

Operating Systems. 05. Threads. Paul Krzyzanowski. Rutgers University. Spring 2015

1 Posix API vs Windows API

Shared Address Space Computing: Programming

MatrixSSL Developer s Guide

Libmonitor: A Tool for First-Party Monitoring

SQLITE C/C++ TUTORIAL

An Incomplete C++ Primer. University of Wyoming MA 5310

CPE453 Laboratory Assignment #2 The CPE453 Monitor

CS 33. Multithreaded Programming V. CS33 Intro to Computer Systems XXXVII 1 Copyright 2015 Thomas W. Doeppner. All rights reserved.

Programming the Cell Multiprocessor: A Brief Introduction

3 - Lift with Monitors

Multi-core Programming System Overview

Middleware. Peter Marwedel TU Dortmund, Informatik 12 Germany. technische universität dortmund. fakultät für informatik informatik 12

CS420: Operating Systems OS Services & System Calls

C++ DATA STRUCTURES. Defining a Structure: Accessing Structure Members:

Win32 API Emulation on UNIX for Software DSM

Kernel Types System Calls. Operating Systems. Autumn 2013 CS4023

How To Understand How A Process Works In Unix (Shell) (Shell Shell) (Program) (Unix) (For A Non-Program) And (Shell).Orgode) (Powerpoint) (Permanent) (Processes

Recursion C++ DSP Toolkit Libraries DM6437 Cross Development

JAVA - MULTITHREADING

Operating Systems and Networks

OPERATING SYSTEM SERVICES

Channel Access Client Programming. Andrew Johnson Computer Scientist, AES-SSG

NS3 Lab 1 TCP/IP Network Programming in C

3.5. cmsg Developer s Guide. Data Acquisition Group JEFFERSON LAB. Version

FreeBSD Developer Summit TrustedBSD: Audit + priv(9)

FAME Operating Systems

C++ INTERVIEW QUESTIONS

Netscape Internet Service Broker for C++ Programmer's Guide. Contents

An API for Reading the MySQL Binary Log

System Structures. Services Interface Structure

Get the Better of Memory Leaks with Valgrind Whitepaper

SMTP-32 Library. Simple Mail Transfer Protocol Dynamic Link Library for Microsoft Windows. Version 5.2

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Building Applications Using Micro Focus COBOL

Introduction to Multicore Programming

LLVMLinux: Embracing the Dragon

Last Class: OS and Computer Architecture. Last Class: OS and Computer Architecture

Virtuozzo Virtualization SDK

Operating System: Scheduling

How To Run A Test File Extension On A Rexx (Unix) On A Microsoft Linux (Amd64) (Orchestra) (For Windows) (

CSI 402 Lecture 13 (Unix Process Related System Calls) 13 1 / 17

RTI Database Integration Service. Getting Started Guide

BLM 413E - Parallel Programming Lecture 3

CSE 265: System and Network Administration

IBM Informix. IBM Informix Object Interface for C++ Programmer s Guide. Version 3.50 SC

RTI Monitoring Library Getting Started Guide

Basics of I/O Streams and File I/O

CSC230 Getting Starting in C. Tyler Bletsch

Overview. Lecture 1: an introduction to CUDA. Hardware view. Hardware view. hardware view software view CUDA programming

CSE 265: System and Network Administration. CSE 265: System and Network Administration

Multi-Threading Performance on Commodity Multi-Core Processors

The Double-layer Master-Slave Model : A Hybrid Approach to Parallel Programming for Multicore Clusters

JP1/Base Function Reference

An Open Source Wide-Area Distributed File System. Jeffrey Eric Altman jaltman *at* secure-endpoints *dot* com

Intro to GPU computing. Spring 2015 Mark Silberstein, , Technion 1

An Overview of Java. overview-1

CPSC 226 Lab Nine Fall 2015

DATA STRUCTURE - STACK

New Features in BSF4ooRexx (Camouflaging Java as oorexx)

Grundlagen der Betriebssystemprogrammierung

Kernel comparison of OpenSolaris, Windows Vista and. Linux 2.6

Software Verification with VeriFast: Industrial Case Studies

The 2014 Edition of BSF4ooRexx (for Windows, Linux, MacOSX)

IT304 Experiment 2 To understand the concept of IPC, Pipes, Signals, Multi-Threading and Multiprocessing in the context of networking.

CSE 265: System and Network Administration. CSE 265: System and Network Administration

Operating System Structures

Member Functions of the istream Class

CPU Scheduling Outline

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Project No. 2: Process Scheduling in Linux Submission due: April 28, 2014, 11:59pm

Implementing Rexx Handlers in NetRexx/Java/Rexx

Konzepte objektorientierter Programmierung

CS 103 Lab Linux and Virtual Machines

Lab 2: Swat ATM (Machine (Machine))

Software Development to Control the Scorbot ER VII Robot With a PC

IPC. Semaphores were chosen for synchronisation (out of several options).

64-Bit NASM Notes. Invoking 64-Bit NASM

OMPT: OpenMP Tools Application Programming Interfaces for Performance Analysis

Jorix kernel: real-time scheduling

NaviCell Data Visualization Python API

To Java SE 8, and Beyond (Plan B)

Kiko> A personal job scheduler

Operating System Tutorial

Applying Clang Static Analyzer to Linux Kernel

GDB Tutorial. A Walkthrough with Examples. CMSC Spring Last modified March 22, GDB Tutorial

Tasks Schedule Analysis in RTAI/Linux-GPL

Computer Systems II. Unix system calls. fork( ) wait( ) exit( ) How To Create New Processes? Creating and Executing Processes

OMPT and OMPD: OpenMP Tools Application Programming Interfaces for Performance Analysis and Debugging

APACHE WEB SERVER. Andri Mirzal, PhD N

OpenGL Insights. Edited by. Patrick Cozzi and Christophe Riccio

Visual C Tutorial

Transcription:

C++ MULTITHREADING http://www.tutorialspoint.com/cplusplus/cpp_multithreading.htm Copyright tutorialspoint.com Multithreading is a specialized form of multitasking and a multitasking is the feature that allows your computer to run two or more programs concurrently. In general, there are two types of multitasking: process-based and thread-based. Process-based multitasking handles the concurrent execution of programs. Thread-based multitasking deals with the concurrent execution of pieces of the same program. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. C++ does not contain any built-in support for multithreaded applications. Instead, it relies entirely upon the operating system to provide this feature. This tutorial assumes that you are working on Linux OS and we are going to write multi-threaded C++ program using POSIX. POSIX Threads, or Pthreads provides API which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD, GNU/Linux, Mac OS X and Solaris. Creating Threads: There is following routine which we use to create a POSIX thread: pthread_create (thread, attr, start_routine, arg) Here, pthread_create creates a new thread and makes it executable. This routine can be called any number of times from anywhere within your code. Here is the description of the parameters: Parameter thread attr start_routine arg Description An opaque, unique identifier for the new thread returned by the subroutine. 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. The C++ routine that the thread will execute once it is created. A single argument that may be passed to start_routine. It 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. Terminating Threads: There is following routine which we use to terminate a POSIX thread: pthread_exit (status) Here 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. If 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.

Example: This simple example code creates 5 threads with the pthread_create routine. Each thread prints a "Hello World!" message, and then terminates with a call to pthread_exit. #include <iostream> #define NUM_THREADS 5 void * PrintHello(void * threadid) long tid; tid = (long)threadid; cout << "Hello World! Thread ID, " << tid << endl; for( i=0; i < NUM_THREADS; i++ ) cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i); if (rc) Compile the following program using -lpthread library as follows: $gcc test.cpp -lpthread Now, execute your program which should generate result something as follows: Hello World! Thread ID, 0 Hello World! Thread ID, 1 Hello World! Thread ID, 2 Hello World! Thread ID, 3 Hello World! Thread ID, 4 Passing Arguments to Threads: This example shows how to pass multiple arguments via a structure. You can pass any data type in a thread callback because it points to void as explained in the following example: #include <iostream>

#define NUM_THREADS 5 struct thread_data int thread_id; char * message; ; void * PrintHello(void * threadarg) struct thread_data * my_data; my_data = (struct thread_data *) threadarg; cout << "Thread ID : " << my_data->thread_id ; cout << " Message : " << my_data->message << endl; struct thread_data td[num_threads]; for( i=0; i < NUM_THREADS; i++ ) cout <<"main() : creating thread, " << i << endl; td[i].thread_id = i; td[i].message = "This is message"; rc = pthread_create(&threads[i], NULL, PrintHello, (void *)&td[i]); if (rc) When the above code is compiled and executed, it produces the following result: Thread ID : 3 Message : This is message Thread ID : 2 Message : This is message Thread ID : 0 Message : This is message Thread ID : 1 Message : This is message Thread ID : 4 Message : This is message Joining and Detaching Threads: There are following two routines which we can use to join or detach threads: pthread_join (threadid, status) pthread_detach (threadid) The pthread_join subroutine blocks the calling thread until the specified threadid thread terminates. 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. If a thread is created as detached, it can never be joined. This example demonstrates how to wait for thread completions by using the Pthread join routine.

#include <iostream> #include <unistd.h> #define NUM_THREADS 5 void * wait(void * t) long tid; tid = (long)t; sleep(1); cout << " " << endl; cout << "Thread with id : " << tid << "...exiting " << endl; pthread_attr_t attr; void * status; // Initialize and set thread joinable pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for( i=0; i < NUM_THREADS; i++ ) cout << "main() : creating thread, " << i << endl; rc = pthread_create(&threads[i], NULL, wait, (void *)i ); if (rc) // free attribute and wait for the other threads pthread_attr_destroy(&attr); for( i=0; i < NUM_THREADS; i++ ) rc = pthread_join(threads[i], &status); if (rc) cout << "Error:unable to join," << rc << endl; cout << "Main: completed thread id :" << i ; cout << " exiting with status :" << status << endl; cout << "Main: program exiting." << endl; When the above code is compiled and executed, it produces the following result: Thread with id : 0... exiting

Thread with id : 1... exiting Thread with id : 2... exiting Thread with id : 3... exiting Thread with id : 4... exiting Main: completed thread id :0 exiting with status :0 Main: completed thread id :1 exiting with status :0 Main: completed thread id :2 exiting with status :0 Main: completed thread id :3 exiting with status :0 Main: completed thread id :4 exiting with status :0 Main: program exiting. Loading [MathJax]/jax/output/HTML-CSS/jax.js