Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering

Introduction to Linux – Create Thread (Part 15/24)

By Ashish Vara

How to Create Thread in Linux

We know about thread in Linux. In this tutorial, I will explain how to create thread in Linux with the help of a programming example. Thread must be executed in process. It is much similar to a process. We can say that thread is light weight process and shares the same address space, data and attribute of process. Thread is single sequence stream within the process. It is like some mathematical or some small function of code which is run within the process. Refer to the tutorial Thread in Linux.

create-thread

Fig. 1: Overview of Thread in LINUX

 

The POSIX thread libraries are available which include different functions regarding the thread. It is a standard library named <pthread.h>.

You can create a new thread by pthread_t data type.

System Call pthread_create ( )

System call pthread_create ( ) creates a new thread in the current process.

Synopsis of function is:

       #include <pthread.h>

    int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

Execution of new thread starts by invoking start_routine ( ) and arg is passing argument of routine. New thread name is pointed by thread and the attr argument points to a pthread_attr_t structure whose contents are used to determine attributes for the new thread.  The thread is created with default attributes if attr is NULL. If pthread_create ( ) is successfully called, it stores the ID of new thread in buffer pointed to thread.

The system call pthread_create() returns zero if  new thread is successfully created and it returns error number if not created due to any one of the following errors:

EAGAIN –   Requirement of resources are not fully satisfied to create another thread.

EAGAIN –   This error will occur when the number of thread creation limits reaches at threshold level.             

EINVAL – It indicates the attr is not valid for creating new thread

EPERM – No permission to set the scheduling policy and parameters specified in attr.     

Let’s explain how to create thread by system call thread_create ( ) and how to work upon it. Here I have described a simple demo of creation of thread in c programming.  If you are unaware about the basics of C language, refer to the tutorial how to make first C programming in Linux.

 

//*******************************thread_demo.c*******************************//

 

#include<stdio.h>

#include<string.h>

#include<pthread.h>

#include<stdlib.h>

#include<unistd.h>

 

void *eventToPrint( void *str );

int main(void)

{

    int result1 ,result2;

    char *msg = “Welcome User”;

    pthread_t thread1, thread2;

    result1 = pthread_create (&thread1, NULL, eventToPrint,(void*) msg);

    if (result1 == 0)

    {

            printf(“n Thread 1 created successfullyn”);

    }

    else

    {

           perror(“Sorry….Thread 1 is not created!!!n”);

           exit(EXIT_FAILURE);

    }

    result2 = pthread_create (&thread1, NULL, eventToPrint, “Hello Engineersgarage”);

    if (result2 == 0)

    {

            printf (“n Thread 2 created successfullyn”);

    }

    else

    {

           perror(“Sorry….Thread 2 is not created!!!n”);

           exit(EXIT_FAILURE);

    }

    pthread_join( thread1, NULL);

    pthread_join( thread2, NULL);

    exit(EXIT_SUCCESS);

    return 0;

}

void *eventToPrint( void *str )

{

     char *display;

     display = (char *) str;

     printf(“%s n”, display);

}

 

//*******************************thread_demo.c*******************************//

 

Save the file in directory and compile it. After the successful compilation, run the executable file from command terminal. You may refer to the tutorial how to make first C programming in Linux if you not aware of compilation and execution process.

Here I have created two new threads for display message. First thread displays “Welcome User” and second thread displays “Hello Enigneersgarage” on screen. Before calling pthread_ create ( ), I have assigned address to thread by thread_t data type. When pthread_create ( ) is calling it will be passed by first argument pthread_t *thread and it will store the ID in address space.

The function eventToPrint ( ) displays the thread message on screen. Message is displayed by routine function eventToPrint ( ) which is passed as sub routine argument in system call. I declared the message of first thread as outside of system call and passed by reference. Message of second thread is directly defined in argument arg with system call pthread_create ( ).

If first thread is created successfully, it returns zero and displays the following message in screen:

               Thread 1 created successfully

It displays the error number with following message if creation of thread is failed:

               Sorry….Thread 1 is not created!!!

Same thing happens when second thread is created.

The system call pthread_join ( ) waits for completion of the task of thread. If you do not join the thread, it terminates as soon as it is completed. If pthread_join ( ) is cancelled to join  thread, it returns zero and current thread remains joined. I attached both  the threads by pthread_join ( )  waiting for one thread when another thread is being executed.

Output of above code will be printed on screen as follows:

               Thread 1 created successfully

               Thread 2 created successfully

               Welcome User

               Hello Engineersgarage

 


Filed Under: Tutorials

 

Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


Featured Tutorials

  • PS2 Keyboard To Store Text In SD Card Using Arduino Circuit Setup On Breadboard
    How To Use PS2 Keyboard To Store Text In SD Card Using Arduino- (Part 42/49)
  • Wireless Path Tracking System Using Mouse, XBee And Arduino Circuit Setup On Breadboard
    How To Make A Wireless Path Tracking System Using Mouse, XBee And Arduino- (Part 43/49)
  • How to Make a Wireless Keyboard Using Xbee with Arduino- (Part 44/49)
  • Making Phone Call From GSM Module Using Arduino Circuit Setup On Breadboard
    How to Make Phonecall From GSM Module Using Arduino- (Part 45/49)
  • How to Make a Call using Keyboard, GSM Module and Arduino
    How To Make A Call Using Keyboard, GSM Module And Arduino- (Part 46/49)
  • Receiving SMS Using GSM Module With Arduino Prototype
    How to Receive SMS Using GSM Module with Arduino- (Part 47/49)

Stay Up To Date

Newsletter Signup

Sign up and receive our weekly newsletter for latest Tech articles, Electronics Projects, Tutorial series and other insightful tech content.

EE Training Center Classrooms

EE Classrooms

Recent Articles

  • How to interface a DS18B20 temperature sensor with MicroPython’s Onewire driver
  • What is a low power design?
  • Renesas partners with Tata to accelerate progress in advanced electronics
  • STMicroelectronics’ new touchscreen controller for smartphones enables longer runtime
  • Samsung unveils ISOCELL image sensor with industry’s smallest 0.56μm pixel

Most Popular

5G 555 timer circuit 8051 ai Arduino atmega16 automotive avr bluetooth dc motor display Electronic Part Electronic Parts Fujitsu ic infineontechnologies integratedcircuit Intel IoT ir lcd led maximintegratedproducts microchip microchiptechnology Microchip Technology microcontroller microcontrollers mosfet motor powermanagement Raspberry Pi remote renesaselectronics renesaselectronicscorporation Research samsung semiconductor sensor software STMicroelectronics switch Technology vishayintertechnology wireless

RSS EDABOARD.com Discussions

  • Effect of variable gain amplifier and LNA on the input RF signal's phase
  • How do you find the angle made by two isosceles triangles in a kite?
  • MWO - EM Structure missing
  • HF preamplifier with threshold?
  • Does Monostable pulse stay HIGH whilst input pulse is HIGH?

RSS Electro-Tech-Online.com Discussions

  • Lighting a .010 green fiber optic with led
  • Help wanted to power an AC120v induction motor ( edited from Brushless motor - thank you @SHORTBUS= )
  • HELP NEEDED
  • NOR gate oscillator in LTspice not working
  • intro to PI
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • About Us
  • Contact Us
  • Advertise

Copyright © 2022 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy | Advertising | About Us

Search Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
    • Design Guides
      • WiFi & the IOT Design Guide
      • Microcontrollers Design Guide
      • State of the Art Inductors Design Guide
  • Women in Engineering