Detailed introduction to multi-threaded programming in C language under Linux

黄舟
Release: 2017-10-14 11:00:42
Original
2108 people have browsed it

This article mainly introduces multi-threaded programming in C language under Linux. Friends who need it can refer to it

When we write Linux services, we often use Linux multi-threading technology to improve Program Performance

#Some little knowledge of multi-threading:

An application can start several threads.

Thread (Lightweight Process, LWP) is the smallest unit of program execution.

Generally, the simplest program will have at least one thread, which is the program itself, that is, the main function (a single-threaded process can simply be considered as a process with only one thread)

One thread is blocked It will not affect other threads.

Multi-threaded processes can utilize system CPU resources as much as possible.

1Create a thread

First go to a simple code that creates a thread in a process, and then slowly go deeper.


#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void * func(void * arg)
{
 printf("func run...\n");
 return NULL;
}
int main()
{
 pthread_t t1;
 int err = pthread_create(&t1,NULL,func,NULL);
 if(err!=0)
 {
  printf("thread_create Failed:%s\n",strerror(errno));
 }else{
  printf("thread_create success\n");
 }
 sleep(1);
 return EXIT_SUCCESS;
}
int pthread_create(pthread_t *thread,const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg);
Copy after login

In the main function we call the above function to create a thread.

Function parameters:

The first parameter: pthread_t represents the unique identifier of the created thread. It is a structure. After we create it, we need to change the structure's The pointer is passed.

The second parameter: pthread_attr_t, represents some configurations for creating this thread, such as the size of the allocation stack, etc. . Generally we can fill in NULL, which represents the default thread creation configuration

The third parameter: represents the address of a function. When creating a thread, this function will be called. The return value of the function is void*, the parameters of the function. Also void*, the general format is like void * func(void * arg){}

The fourth parameter: represents the parameter passed by calling the third function

Function return value:

The function returns 0 successfully. If it is not equal to 0, it means the function call failed. At this time, the specific error can be printed through strerror(errno).

Note: Each thread has a copy of errno, and different threads have different errno

Finally compiled by gcc


gcc 1createthread.c -c -o 1createthread.o
gcc 1createthread.o -o thr1 -lpthread
Copy after login

When compiling, you need to add -lpthread to link the libpthread.so dynamic library, otherwise it will prompt that the function cannot be found

The function call returns the result

Question: Why is the sleep function called?

Answer: Maybe the newly created thread ends before the main thread reaches the printing method, and the main thread ends, all The thread will all end.

2 Thread hangs

#Sometimes we create another thread in a thread, and the main thread has to wait until the created thread returns. , the main thread exits only after obtaining the return value of the thread. At this time, you need to use thread suspension.


int pthread_join(pthread_t th, void **thr_return);。
Copy after login

The pthread_join function is used to suspend the current thread until the thread specified by th terminates.


#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void * func(void * arg)
{
 int i=0;
 for(;i<5;i++)
 {
  printf("func run%d\n",i);
  sleep(1);
 }
 int * p = (int *)malloc(sizeof(int));
 *p=11;
 return p;
}
int main()
{
 pthread_t t1,t2;
 int err = pthread_create(&t1,NULL,func,NULL);
 if(err!=0)
 {
  printf("thread_create Failed:%s\n",strerror(errno));
 }else{
  printf("thread_create success\n");
 }
 void *p=NULL;
 pthread_join(t1,&p);
 printf("线程退出:code=%d\n",*(int*)p);
 return EXIT_SUCCESS;
}
Copy after login

Function execution result

Our main function has been waiting for the created thread to finish executing, and got the thread Return value at the end of execution

3 Thread termination

exit() function when the process terminates, so what is thread termination?

Three situations of thread termination:

The thread just returns from the startup function, and the return value is the exit code of the thread.

Threads can be canceled by other threads in the same process.

The thread calls pthread_exit.


#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void * func(void * arg)
{
 int i=0;
 while(1)
 {
  if(i==10)
  {
   int * p = (int *)malloc(sizeof(int));
   *p=11;
   pthread_exit(p);
  }
  printf("fun run %d\n",i++);
  sleep(1);
 }
 return NULL;
}
int main()
{
 pthread_t t1,t2;
 int err = pthread_create(&t1,NULL,func,NULL);
 if(err!=0)
 {
  printf("thread_create Failed:%s\n",strerror(errno));
 }else{
  printf("thread_create success\n");
 }
 void *p=NULL;
 pthread_join(t1,&p);
 printf("线程退出:code=%d",*(int*)p);
 return EXIT_SUCCESS;
}
void pthread_exit(void *arg);
Copy after login

The parameters of the pthread_exit function are the same as when the normal thread ends return, and will be obtained by the main thread waiting for it to end.

Function operation result:

4 Thread separation


int pthread_detach(pthread_t th);
Copy after login

The pthread_detach function puts the thread in a detached state.

If you are not waiting for a thread and are not interested in the return value of the thread, you can set the thread to the detached state and let the system automatically recycle the resources it occupies when the thread exits.

A thread cannot call pthread_detach itself to change itself to the detached state. It can only call pthread_detach by other threads.

5 Thread cancellation


##

int pthread_cancel(pthread_t th);
Copy after login

The pthread_cancel function allows one thread to cancel another thread specified by th.

The function returns 0 if successful, otherwise it returns non-0.


#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void * func1(void * arg)
{
 while(1)
 {
  printf("fun run...\n");
  sleep(1);
 }
 return NULL;
}
int main()
{
 pthread_t t1;
 if(pthread_create(&t1,NULL,func1,NULL)!=0)
 {
  printf("thread_create Failed:%s\n",strerror(errno));
  return -1;
 }
 sleep(5);
 pthread_cancel(t1);
 pthread_join(t1,NULL);
 return EXIT_SUCCESS;
}
Copy after login

Function execution result:

上面我们说过创建一个线程函数pthread_create的第二个参数,用来决定创建线程的一些初始化状态,这里我们 举个例子,改线程一创建就是分离状态的线程(

上面介绍了pthread_detach函数的概念,可以通过pthread_attr_t在创建线程的时候就指定线程属性为detach,而不用创建以后再去修改线程属性。

先上一段代码:


#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void * func(void * arg)
{
 int i=0;
 for(;i<5;i++)
 {
  printf("func run%d\n",i);
  sleep(1);
 }
 int * p = (int *)malloc(sizeof(int));
 *p=11;
 return p;
}
int main()
{
 pthread_t t1;
 pthread_attr_t attr;//申明一个attr的结构体
 pthread_attr_init(&attr);//初始化结构体
 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);//设置线程为分离线程
 int err = pthread_create(&t1,&attr,func,NULL);
 if(err!=0)
 {
  printf("thread_create Failed:%s\n",strerror(errno));
 }else{
  printf("thread_create success\n");
 }
 pthread_attr_destroy(&attr);
 pthread_join(t1,NULL);
 printf("主线程退出\n");
 return EXIT_SUCCESS;
}
Copy after login

pthread_attr_t就是我们要传入的参数的结构体,一般申明的步骤有

1,申明一个pthread_attr_t对象

2,函数pthread_attr_init初始化attr结构。

3,设置线程的一些属性,比如pthread_attr_setdetachstate函数就是设置该线程创建的时候为正常状态还是分离状态。

4,函数pthread_attr_destroy释放attr内存空间

pthread_attr_setdetachstate把线程属性设置为下面两个合法值之一:

说明

PTHREAD_CREATE_DETACHED

设置线程为分离状态

PTHREAD_CREATE_JOINABLE

设置线程为正常状态

上面函数运行结果:

因为线程是个分离状态的,所以pthread_join挂起会失效,主线程很快运行结束,程序也就结束了,创建的线程还没来得及运行

线程同步

有时候我们多个线程处理订单扣减库存会遇到这样的问题,两个线程同时进入一段代码先查询库存,两个都查出来为还剩一件库存,第一个线程用掉这个库存后,将库存变为0,但是第二个线程刚才也查出来为1了,所以他还认为有库存,

这个时候操作就会引发我们想不到的意外,库存变为负数了!!所以这个时候就需要使用线程的同步!!

先上一段代码看看效果:


#include<pthread.h>
#include<stdio.h>
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
void * func(void * arg)
{
 int threadno =*(int*)arg;
 int i=0;
 for(;i<10;i++)
 {
  printf("%d thread%d \n",threadno,i);
  sleep(1);
 }
 return NULL;
}
int main()
{
 pthread_t t1,t2;
 int i1=1,i2=2;
 pthread_create(&t1,NULL,func,&i1);
 pthread_create(&t2,NULL,func,&i2);
 pthread_join(t1,NULL);
 pthread_join(t2,NULL);
 printf("主线程退出\n");
 return EXIT_SUCCESS;
}
Copy after login

函数运行结果:

可以看到两个线程是没有规律的争相处理的,如果这段代码是扣减库存就完蛋啦!,所以我们要对这段代码进行加锁,同一时刻只能有一个线程进入操作!

先上代码:


#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * func(void * arg)
{
 pthread_mutex_lock(&mutex);//对mutex加锁,其他线程进入后将会挂起,知道这个锁被解锁
 int threadno =*(int*)arg;
 int i=0;
 for(;i<10;i++)
 {
  printf("%d thread%d \n",threadno,i);
  sleep(1);
 }
 pthread_mutex_unlock(&mutex);
 return NULL;
}
int main()
{
 pthread_t t1,t2;
 int i1=1,i2=2;
 pthread_create(&t1,NULL,func,&i1);
 pthread_create(&t2,NULL,func,&i2);
 pthread_join(t1,NULL);
 pthread_join(t2,NULL);
 printf("主线程退出\n");
 return EXIT_SUCCESS;
}
Copy after login

函数运行结果:

可以看到第二个线程先进入后一直运行结束,对mutex解锁后,第一个线程才能进方法里面运行!否则会挂起,一直等到锁被解锁!

PTHREAD_MUTEX_INITIALIZER是初始化一个快速锁的宏定义。


pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
Copy after login

加锁解锁函数:


int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
Copy after login

总结

The above is the detailed content of Detailed introduction to multi-threaded programming in C language under Linux. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!