linux Thread summary

Multithreading Concepts

definition

Thread is the flow of execution within a process, a process has at least one thread, the thread has its own private resources will also share resources and processes.

Thread unique resources

  • The thread descriptor
  • register
  • Thread stacks
  • errno
  • Signal mask
  • Real-time scheduling policy

Threads and processes to share resources

  • Global Variables
  • stack
  • Snippet
  • File descriptor table
  • Process ID and group ID
  • Each signal processing mode
  • The current working directory

The difference between threads and processes

  • A thread is the smallest unit of resource scheduling, resource allocation process when the smallest unit of
  • Process is a running event, the thread is a path of execution process
  • Resources can not be shared between processes, and where the threads share the process address space and other resources. At the same time also has its own thread stack and stack pointer, program counter and other registers.
  • Process has its own separate address space, but there is no thread, the thread must rely on the process exist.

Create a thread

#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);

Parameters:
1. Thread: return thread ID
2. attr: Thread properties, can be manually set (described in detail below the thread attributes)
3. by start_routine: function address of the function thread of execution
4. arg: a thread of execution parameters of the function
return value :
returns 0 on success, failure to return an error code.

Thread termination

There are three ways to terminate a thread.
1. Return a return.
2. Use the pthread_exit ();

#include <pthread.h>
void pthread_exit(void *retval);

Parameters:
retval: save the thread exit code, the pointer must be a global variable or heap opened.

3. to pthread_cancel ()

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

Parameters:
the Thread: the end of the thread ID (can end any thread)
Return value:
returns 0 on success, failure to return an error code.
Terminate the thread can not exit (), which is a way to terminate the process.

Waiting and separation thread

Why do we need to wait for a thread

  • Do not wait, do not automatically release resources after the end of the thread.
  • Can lead to excessive thread descriptor is occupied, you can not create a new thread.

Thread wait function

#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);

Parameters:
the Thread: waiting thread ID
retval: save and exit status code
return value:
returns 0 on success, failure to return an error code.

Thread separation

When we do not care about the exit status of the thread, the thread end just hope the system will automatically clean up and release resources, then we can use the thread separation.

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

Parameters:
Thread: separate thread ID
Return Value:
returns 0 on success, failure error code is returned.
Once the thread is pthread_detach () separated, can not be reused pthread_join () get their status, and can no longer return to the link status.

Thread Attributes

In front of the pthread_create () function when it comes to pthread_attr_t * attr thread attributes, we can manually set the thread attributes.

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 attribute this one, this is just a simple list, we need to grasp the deeper access to information on their own.

The advantages and disadvantages thread

Advantages thread

  • Create a thread to create a process cost than the cost much less.
  • Compared with switching between processes, switching between threads operating system much less work to be done.
  • Thread consumes much less resources than the process.
  • You can take full advantage of the number of parallel multi-processor.
  • While waiting for the end of the slow I / O operations, the program may perform other computing tasks.
  • Compute-intensive applications, multi-processor operation, may be calculated across multiple computing threads.
  • I / O intensive applications, in order to improve performance, the I / O operations overlap, a different thread may wait for I / O operations.

Shortcoming thread

  • Performance loss
  • Robustness reduced.
  • Lack of access control
  • Increase the difficulty of programming
  • Multithreading support is not good for GDB
  • Multithreading is not good for signal support

The thread mutually exclusive

Mutex

Mutex

  1. Defined mutex: pthread_mutex_t mutex;
  2. Initialization: pthread_mutex_init (& mutex, NULL);
  3. 上锁:pthread_mutex_lock(&mutex);
  4. 解锁:pthread_mutex_unlock(&mutex);
  5. 销毁:pthread_mutex_destroy(&mutex);

Spinlocks

  1. Defined spinlock: pthread_spinlock_t spin;
  2. 初始化:int pthread_spin_init(pthread_spinlock_t *lock, int pshared);
  3. 上锁:int pthread_spin_lock(pthread_spinlock_t *lock);
  4. 解锁:int pthread_spin_unock(pthread_spinlock_t *lock);
  5. 销毁锁:int pthread_spin_destroy(pthread_spinlock_t *lock);

The difference between the spin lock mutex

The difference between the spin locks and exclusive: the mutex when resistance in pthread_mutex_lock, giving up CPU, so that others using the CPU. When the spin lock blocked spin_lock, does not release the CPU, the CPU can keep asking not use

Read-Write Lock

  1. pthread_rwlock_t lock;
  2. 初始化:int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,const pthread_rwlockattr_t *restrict attr);
  3. 读锁:int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
  4. 写锁:int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
  5. 解锁:int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);
  6. 销毁锁:int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);

Read share, read and write exclusive, exclusive write, write locks priority.

Synchronize

Condition variable

  1. Condition variable is defined: pthread_cond_t cond;
  2. Initialization 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 a lock environment mutex useless
        if the environment in a lock, unlock the mutex
        when return wait, the mutex is set to the original state
  4. That the condition is satisfied: int pthread_cond_signal (pthread_cond_t * cond);
  5. Variables for destruction: int pthread_cond_destroy (pthread_cond_t * cond);

Integrated 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;
}
Published 94 original articles · won praise 237 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_38646470/article/details/80423458