Take you to learn multithreaded programming

Source: Internet
Author: User
Tags mutex

Thread Concept Definition

A thread is a flow of execution inside a process, and a process has at least one thread, and the thread has its own private resource and it shares resources with the process.

Thread-Unique Resources
    • Thread descriptors
    • Register
    • Thread Stacks
    • Errno
    • Signal Mask
    • Real-Time scheduling strategy
Resources shared by threads and processes
    • Global variables
    • Heap
    • Code snippet
    • File Descriptor Descriptor
    • Process ID and Group ID
    • How each signal is processed
    • Current working directory

      The difference between threads and processes
    • A thread is the smallest unit of resource scheduling, the smallest unit of resource allocation during a process
    • A process is a program run activity, and a thread is an execution path in a process
    • Resources cannot be shared between processes, and threads share the address space and other resources of the process in which they reside. At the same time the thread also has its own stack and stack pointers, program counters and other registers.
    • The process has its own independent address space, and the thread does not, and the thread must depend on the process to exist.
Creation of Threads
#include <pthread.h>int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

Parameters:

    1. Thread: Returns the ID of the thread
    2. attr: Thread properties can be set manually (the thread properties are described in detail below)
    3. Start_routine: Function Address of the function executed by the thread
    4. ARG: Parameters of the thread execution function
      return value:
      Successful return 0, failure returns error code. Termination of the thread

      There are three ways of terminating a thread.

    5. Return with return.
    6. With Pthread_exit ();
      #include <pthread.h>void pthread_exit(void *retval);

      Parameters:
      retval: Save thread exit code, <font color= "#dd00dd" > this pointer must be a global variable or a heap open. </font><br/>

    7. With Pthread_cancel ()
      #include <pthread.h>int pthread_cancel(pthread_t thread);

      Parameters:
      Thread: End-of-Threads ID (can end any thread)
      return value:
      Successful return 0, failure returns error code.
      The termination of a thread cannot be used with exit (), which is how the process terminates.

Why threads need to wait for a thread to wait and detach
  • Does not wait, the resource is not freed automatically when the thread ends.
  • Causes the multithreading descriptor to be consumed and the new thread cannot be created. Thread wait function
    #include <pthread.h>int pthread_join(pthread_t thread, void **retval);

    Parameters:
    Thread: The ID of the waiting thread
    RetVal: Save exit status Code
    return value:
    Successful return 0, failure returns error code.

    Thread separation

    We can use thread separation when we do not care about the exit state of the thread, just want the thread to end the system to automatically clean up and release the resources.

    #include <pthread.h>int pthread_detach(pthread_t thread);

    Parameters:
    Thread: Detached thread ID
    return value:
    Successful return 0, failure returns error code.
    Once a thread is separated by Pthread_detach (), it can no longer get its state by using Pthread_join (), and it can no longer return to the link state.

    Thread Properties

    In front of the pthread_create () function, the pthread_attr_t *attr thread properties are involved, and we can set the thread properties manually.

    int pthread_attr_init(pthread_attr_t *attr);//初始化线程属性int pthread_attr_destroy(pthread_attr_t *attr);//销毁线程属性对象
    Detach state        = PTHREAD_CREATE_JOINABLE//分离属性int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate);//设置分离属性int pthread_attr_getdetachstate(pthread_attr_t *attr, int *detachstate);//获得分离属性Scope               = PTHREAD_SCOPE_SYSTEM//抢夺资源范围Inherit scheduler   = PTHREAD_INHERIT_SCHED//是否继承线程调度策略Scheduling policy   = SCHED_OTHER//调度策略Scheduling priority = 0//调度优先级Guard size          = 4096 bytes//线程栈之间的安全区Stack address       = 0x40196000//自己指定线程栈Stack size          = 0x201000 bytes//栈的大小

    Thread properties This piece, this article is just a simple list, a deeper grasp of the need for people to consult their own information.

    Advantages of threads with advantages and disadvantages of threads
  • The cost of creating a thread is much smaller than the cost of creating a process.
  • Switching between threads has much less work to do than switching between processes.
  • Threads consume much less resources than processes.
  • Can take full advantage of the number of concurrent processors.
  • When you wait for a slow I/O operation to finish, the program performs other compute tasks.
  • Compute-intensive applications, multi-processor run, compute can be distributed across multiple threads.
  • I/O intensive applications, in order to improve performance, overlap I/O operations, and threads can wait for different I/O operations. Disadvantages of threading
  • Performance loss
  • Decreased robustness.
  • Lack of access control
  • Increased programming difficulty
  • Multithreaded support for GDB is not good
  • Multithreading to signal support bad thread mutex mutex mutex
    1. Define mutex: pthread_mutex_t mutex;
    2. Initialization: Pthread_mutex_init (&mutex,null);
    3. Lock: Pthread_mutex_lock (&mutex);
    4. Unlock: Pthread_mutex_unlock (&mutex);
    5. Destroyed: Pthread_mutex_destroy (&mutex); spin lock
    6. Define spin Lock: pthread_spinlock_t spin;
    7. Initialize: int pthread_spin_init (pthread_spinlock_t *lock, int pshared);
    8. Lock: Int Pthread_spin_lock (pthread_spinlock_t *lock);
    9. Unlock: int pthread_spin_unock (pthread_spinlock_t *lock);
    10. Destroy Lock: int Pthread_spin_destroy (pthread_spinlock_t *lock);
The difference between spin lock and mutual exclusion lock

The difference between a spin lock and a mutex: the mutex is when the Pthread_mutex_lock is blocked, and the CPU is discarded so that others can use it. Spin lock blocking at Spin_lock, will not release the CPU, constantly ask the CPU can use the

Read/write Lock
    1. pthread_rwlock_t lock;
    2. Initialize: int pthread_rwlock_init (pthread_rwlock_t restrict rwlock,const pthread_rwlockattr_t restrict attr);
    3. Read lock: int pthread_rwlock_rdlock (pthread_rwlock_t *rwlock);
    4. Write Lock: int pthread_rwlock_wrlock (pthread_rwlock_t *rwlock);
    5. Unlock: int pthread_rwlock_unlock (pthread_rwlock_t *rwlock);
    6. Destroy Lock: int Pthread_rwlock_destroy (pthread_rwlock_t *rwlock);

Read-read sharing, read and write exclusive, write exclusive, write lock priority.

Synchronization condition Variable
    1. Define condition variables: pthread_cond_t cond;
    2. Initialize condition variable: int pthread_cond_init (pthread_cond_t restrict cond,const pthread_condattr_t restrict attr);
    3. Wait condition: int pthread_cond_wait (pthread_cond_t restrict cond,pthread_mutex_t restrict mutex);
      If not used in the lock environment, the mutex is a dummy
      If the mutex is unlocked in the context of a lock
      When wait returns, the mutex is placed in its original state
    4. satisfies the condition: int pthread_cond_signal (pthread_cond_t *cond);
    5. Destroy condition variable: int Pthread_cond_destroy (pthread_cond_t *cond);
Comprehensive case
pthread_mutex_t mutex;//创建互斥量int a = 0;int b = 0;void *r1(void* arg) //线程1执行函数{    while(1)    {        pthread_mutex_lock(&mutex);//上锁        a++;        b++;        if(a != b)        {            printf("%d != %d\n",a,b);        }        pthread_mutex_unlock(&mutex);//解锁    }}void *r2(void* arg)//线程2执行函数{    while(1)    {        pthread_mutex_lock(&mutex);        a++;        b++;        if(a != b)        {            printf("%d != %d\n",a,b);        }        pthread_mutex_unlock(&mutex);    }   }int main(void){    pthread_t t1,t2;    pthread_mutex_init(&mutex,NULL);//初始化互斥量    pthread_create(&t1,NULL,r1,NULL);//创建线程    pthread_create(&t2,NULL,r2,NULL);//创建线程    pthread_join(t1,NULL);//线程等待    pthread_join(t2,NULL);    return 0;}

Take you to learn multithreaded programming

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.