In this article we will discuss the encapsulation of threads thread;
One, thread class (threads):
Attention:
1, the thread by default is joinable (can be combined state), you need to call the Join function manually (recycle it), you can also set it to detachable ( detached state), the thread will die automatically after the completion of the run;
2, the Thread class uses the static function as the callback function of the pthread_create, because the ordinary member function contains an implicit parameter (the class's object itself), so the function pointer type In addition to the void* parameter, there is a Thread Object, so this does not match the void* (*) (void*) parameter;
The declaration of a class member is as follows:
Private:2 void *runinthread (// Here is the ordinary member function pthread_t tid_; bool Isruning_;
Pthread_create:
1void *thread::runinthread (void *Arg2{3 cout <<"Foo"<<Endl} 5 6 void Thread::start () { 8 // 9 // workaround: Declare runinthread as a static function 10 pthread_create (&tid_, NULL, Thread::runinthread,null) ; //wrong11 isruning_ =< Span style= "color: #0000ff;" >true;
3), through 2), we can successfully implement thread creation, but as in the Runinthread function in the 2), we can only execute our own defined behavior (such as the cout statement), and the user needs the thread to do the work we do not know beforehand, therefore, We re-implement the user's needs through callbacks, and set the run function to pure virtual functions.
The complete code is as follows:
1#ifndef Thread_h_2#define Thread_h_34 #include"NonCopyable.h"5 #include <pthread.h>6 #include <assert.h>7 #include <iostream>8 #include <sys/types.h>9 #include <sys>/Syscall.h10UsingNamespaceStd1112ClassThread:noncopyable13{14Public:15Thread ();16 ~Thread ();1718voidStart ();19voidJoin ();20Virtualvoid run () =0;//Pure virtual function21st22Private:23Staticvoid *runinthread (void *);//The static declaration here indicates that it does not belong to a specific object and belongs to this class.24pthread_t tid_;25boolIsruning_;26};2728Thread::thread ()29:tid_ (0), Isruning_ (False)30{ }31thread::~Thread ()33{34If(Isruning_)35{36Pthread_detach (TID_);37}38}39//So we can define our own My_thread class and re-implement the run function to achieve a specific requirement40void *thread::runinthread (void *arg)//This pointer41{The Thread *pt = static_cast<thread*> (ARG);//Forced conversionsPt->run ();//Call the Run function44ReturnNULL;45}4647voidThread::start ()48{Pthread_create (&tid_, NULL, Thread::runinthread,this);//This pointer points to the thread's this objectIsruning_ =True;51}5253voidThread::join ()54{ isruning_); Pthread_join (tid_,null); Isruning_ = false; pid_t Thread::gettid () const ()----- syscall (sys_gettid); #endif
4, the thread in Linux is essentially a lightweight process, has its own PID, you can write Gettid, through syscall (Sys_gettid) to obtain.
Linux component Encapsulation Three: Thread