C + + Multithreading analysis

Source: Internet
Author: User

we started talking about threads before we first look at these lines before the carrier-process.

Process, which is an instance of an executing program. is an execution activity of a program in its own address space. A process is the basic unit of resource requisition, dispatch, and independent execution. A process consists of two parts:

1. the kernel object that the operating system uses to manage processes. A kernel object is a place that the system uses to hold statistical information about the process, a block of memory allocated within the operating system that is a data structure whose members are responsible for maintaining various information about the object.

2. address space, which includes code and data for all modules that can run, DLL modules, and also includes the space for dynamic memory allocation.

The minimum unit---The operating system schedule for a thread. Threads are included in the process and are the units that are actually executed in the process. A process can execute multiple threads at the same time. Each thread is capable of performing different tasks. This is called multithreading.

Multiple threads in the same process share all of the system resources in the process, such as virtual address space, file descriptor, and signal processing, but multiple threads in the same process have their own call stacks, register environments, and thread-local storage.

for single-core (single-CPU) systems, even though the processor can execute only one thread at a time, the operating system passes through the technology of temporal chip rotation. Switching between different threads allows the user to create the illusion of being able to handle multiple tasks at the same time, a program execution mechanism called multithreaded software.

for multicore (multiple CPUs) systems, this system can perform real multi-threaded multitasking at the same time. This execution mechanism can be called the hardware multithreading technology.

Multi-threaded process as a multi-tasking, concurrent work mode. Of course there are the following advantages:

1), improve application response. This is especially useful for graphical interface programs, where the entire system waits for a very long time to be done. At this point, the program does not respond to keyboard, mouse, menu operations, and the use of multithreading technology. Place a long-consuming operation (time consuming) on a new thread. To avoid such awkward situations.

2), make multi-CPU system more effective.

The operating system guarantees that when the number of threads is not greater than the number of CPUs, different threads execute on different CPUs.

3), improve the program structure. A long and complex process can be considered to be divided into multiple threads and become several independent or semi-independent execution parts. This procedure is beneficial to understanding and alteration.

For example, I write a cross-platform threading sample:

Mutex.h#ifndef heart_mkitheart_mmutex_h#define heart_mkitheart_mmutex_h#ifdef WIN32#include <windows.h> #else         #include <pthread.h> #endif #ifdef win32typedef critical_section mkit_mutex_section #define Mkit_mutex_init :: Initializecriticalsection#define Mkit_mutex_destroy::D eletecriticalsection#define MKIT_MUTEX_LOCK:: E Ntercriticalsection#define mkit_mutex_unlock:: Leavecriticalsection#elsetypedef pthread_mutex_t MKIT_MUTEX_S ection, #define Mkit_mutex_init pthread_mutex_init#define Mkit_mutex_destroy pthread_mutex_destroy#define MKIT _mutex_lock pthread_mutex_lock#define mkit_mutex_unlock pthread_mutex_unlock#endifclass Mutex{public:Mutex () {Mkit_mutex_init (&m_mutex#ifndef _win32, null#endif);} Virtual ~mutex () {Mkit_mutex_destroy (&m_mutex);} virtual void Lock () const {mkit_mutex_lock (&AMP;M_MUTEX);} virtual void Unlock () const {mkit_mutex_unlock (&AMP;M_MUTEX);} Private:mutable mkit_mutex_section M_mutex;}; class Autolock{public:autolock (const mutex& Mutex, BOOL autolocked = True): M_mutex (&mutex), m_locked (true) {if (autolocked) {M_mutex->lock (); m_locked = autolocked;}}; ~autolock () {if (m_locked) {M_mutex->unlock ()}}; Private:const mutex* m_mutex;bool m_locked;}; #ifndef lock#define LOCK (mutex) Autolock Locker (mutex) #endif #endif//heart_mkitheart_mmutex_h

Thread.h#ifndef heart_mkitheart_mthread_h#define heart_mkitheart_mthread_h#include "Mutex.h" #define RET_SUCCEED 0class runnable{public:virtual void Run () = 0;}; Class Thread:public Virtual Runnable{thread (const thread&), const thread& operator= (const thread&);p ublic: Thread (); ~thread (); #ifdef win32static unsigned int WINAPI threadfun (void* t); #elsestatic void* Threadfun (void* t); # Endifint Start (void), int Stop (void), inline bool IsRunning (void) {return m_running;} inline void setrunning (bool x) {m_running = x;} inline unsigned short getwaittime (void) {return m_waittime;} inline void setwaittime (unsigned short utime) {m_waittime = Utime;} inline void setrunnable (runnable* prunnable) {m_runnable = prunnable;}    public:virtual void Run ();p rotected:void watitime (int mTime);p rivate: #ifdef win32handle m_handle;unsigned int M_threadid, #elsepthread_t m_thread_t;pthread_attr_t m_attr; #endifprivate: unsigned shortm_waittime;boolm_running; runnable*m_runnable;    Mutex      M_mutex;}; #endif//heart_mkitheart_mthread_h

Thread.cpp#ifdef win32#include <process.h> #else # include <sys/time.h> #include <sys/types.h> #endif #include "Thread.h" Thread::thread (): M_handle (0), m_runnable (0), m_running (false), M_waittime (+) {}thread::~thread ( ) {Stop ();} void Thread::run () {if (m_runnable) {M_mutex. Lock (); M_runnable->run (); M_mutex. Unlock ();} Watitime (m_waittime);} #ifdef win32unsigned int Thread::threadfun (void* t) #elsevoid * Thread::threadfun (void* t) #endif {Thread *p = (thread*) (t), if (t) {while (p->isrunning ()) {P->run ();} #ifdef win32_endthreadex (0); #elsepthread_exit ((void*) 0); #endif}return Ret_succeed;} int Thread::start (void) {if (! IsRunning ()) {#ifdef Win32m_handle = (handle) _beginthreadex (NULL, 0, Threadfun, this, 0, &m_threadid);//create_ Suspended#elsepthread_attr_init (&m_attr);p thread_attr_setdetachstate (&m_attr, PTHREAD_CREATE_DETACHED); if ( -1 = = Pthread_create (&m_thread_t, &m_attr, Threadfun, this)) {setrunning (false); return-1;} #endifSetRunning (TRUE);} Return RET_SUCCEED;} int thread::stop (void) {if (isrunning ()) {M_mutex. Lock (); Setrunning (false); M_mutex. Unlock ();} #ifdef win32if (M_handle) {:: WaitForSingleObject (M_handle);:: CloseHandle (m_handle); m_handle = NULL;} #endifreturn Ret_succeed;} #ifdef win32void thread::watitime (int mTime) {Sleep (mTime);} #elsepthread_cond_t g_timer_cond;pthread_mutex_t g_timer_mutex;void thread::watitime (int mTime) {struct Timeval temp_ Timeout;gettimeofday (&temp_timeout, 0); struct Timespec timeout;timeout.tv_sec = temp_timeout.tv_sec;timeout.tv_ Nsec = (temp_timeout.tv_usec + mTime * +) * 1000;pthread_cond_timedwait (&g_timer_cond, &g_timer_mutex, &t Imeout);} #endif

Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.

C + + Multithreading analysis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.