Detailed explanation and simple example of multithreading in Linux

Time:2020-2-12

Detailed explanation and simple example of multithreading in Linux

1. concept

Process: a running program.

Thread: multiple execution paths in a program. A more accurate definition is that a thread is a control sequence within a process.

2. Why do we have threads?

It’s too expensive to call a process with fork. You need to let a process do many things at the same time. Threads are very useful.

3. Advantages and disadvantages of threads.

Advantage:

(1) Sometimes it’s useful to make the program seem to be doing two things at the same time. For example, when editing a document, you can count the number of words in the document.
(2) A program mixed with input, calculation and output can be divided into three threads by using threads, so as to change the performance of program execution.
(3) Generally speaking, switching between threads requires less work done by the operating system than switching between processes.

Disadvantages:

(1) Writing threads requires very careful design.
(2) It is much more difficult to debug multithread than single thread.

4. Create thread


#include <pthread.h>
(1)int pthread_create(pthread_t *thread,pthread_attr_t *attr,void *(*start_routine)(void *),void *arg);
pthread_t pthread_self(void);
(2)int pthread_equal(pthread_t thread1,pthread_t thread2);
(3)int pthread_once(pthread_once_t *once_control,void(*init_routine)(void));

Linux system supports POSIX multi-threaded interface, which is called pthread. To write multithreaded programs under Linux, you need to include the header file pthread. H, and use the library libpthread. A when linking.

If you create a thread in the main thread, the program will branch at the place where the thread is created, and become two parts of execution. The creation of thread is completed by pthread “create”. 0 returned successfully.

1. Thread creation: 
int pthread_create(pthread_t thread,pthread_attr_t *attr,void (start_routine)(void ),void *arg); 
pthread_t pthread_self(void); 
Parameter Description: 
Thread: pointer to pthread ﹣ create type, which is used to refer to the newly created thread. 
Attr: used to set the properties of a thread. Generally, no special properties are required, so it can be simply set to null. 
(start_routine) (void): pass the address of the function to be executed by the new thread. 
Arg: parameter of the function to be executed by the new thread. 
If the call succeeds, the return value is 0, and if it fails, the error code is returned. 
2. Thread termination 
void pthread_exit(void *retval); 
Parameter Description: 
Retval: return pointer to an object to be returned by the thread. 
The thread terminates the execution by calling the pthread · exit function and returns a pointer to an object. Note: never use it to return a pointer to a local variable, because after the thread calls the function, the local variable does not exist, which will cause serious program vulnerabilities. 
3. Thread synchronization 
int pthread_join(pthread_t th, void **thread_return); 
Parameter Description: 
Th: the thread to wait. The thread is specified by the identifier returned by pthread ﹐ create. 
Thread'return: a pointer to another pointer, which points to the return value of the thread.

A simple way to create a multithreaded program:


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

void *thread_function(void *arg);

char message[] = "Hello World";

int main()
{
  int res;
  pthread_t a_thread;
  void *thread_result;

  res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
  if (res != 0)
  {
    perror("Thread creation failed!");
    exit(EXIT_FAILURE);
  }

  printf("Waiting for thread to finish.../n");

  res = pthread_join(a_thread, &thread_result);
  if (res != 0)
  {
    perror("Thread join failed!/n");
    exit(EXIT_FAILURE);
  }

  printf("Thread joined, it returned %s/n", (char *)thread_result);
  printf("Message is now %s/n", message);

  exit(EXIT_FAILURE);
}

void *thread_function(void *arg)
{
  printf("thread_function is running. Argument was %s/n", (char *)arg);
  sleep(3);
  strcpy(message, "Bye!");
  pthread_exit("Thank you for your CPU time!");
}

Output result

$. / thread1 [output]:
thread_function is running. Argument was Hello World
Waiting for thread to finish...
Thread joined, it returned Thank you for your CPU time!
Message is now Bye!

The above is the detailed explanation of Linux multithreading example. If you have any questions, please leave a message or go to the community of this site to discuss. Thanks for reading. I hope to help you. Thank you for your support!