linux--Thread (6) __linux

Source: Internet
Author: User
Processes and ThreadsConcept: In Linux, threads are generally considered "lightweight processes", processes are stand-alone units of an application, and threads cannot exist independently, and must be created by a process. The advantages of line threads relative to the process:
Memory data sharing (1. Processes need to run independently of each segment, and threads can run multiple simultaneous runs in one process, sharing the same memory; 2. Data general, high efficiency)
Increase response speed
CPU systems are more efficient because threads run on different CPUs
Improved program structure because one process splits into multiple threads, and individual threads can manage Implementing Basic Functions

BASIC programming
Common thread functions
Pthread_attr_init Initialize thread properties (to initialize before create)
Pthread_create Create a thread
Pthead_exit Thread exits (exit (0) function when exiting process)
Pthread_join other threads to wait for a thread to exit (free related memory resources)
The memory cannot be freed automatically after the thread is finished, so use a function to release
Pthread_detach makes the child thread itself have the ability to reclaim memory resources
Pthread_cancel the current thread will kill other threads
Pthread_self to obtain the current thread's flag

Specific functions

Thread creation
The function prototype is:
int pthread_create (pthread_t* thread,
Pthread_attr_t* attr,
void (*start_routine) (void),
void * arg);

The first parameter is a pointer to the pthread_t type, which points to a flag that holds the thread created after the thread was created successfully.
The second parameter indicates the attributes that the created thread can have
The third argument is a function pointer that points to the thread's implementation function
The fourth argument arg is a void * type, and this parameter points to the parameter thread that is required when the actual threading function executes
There are two ways to exit a thread:
The thread function ends, for example, to the end of the function or to exit with return. The thread ends naturally. This is the most common way
You can explicitly call Pthread_exit () to end a thread execution
The function prototype is:
void Pthread_exit (Void*retval);
parameter is the return value to the thread
A thread's exit cannot simply use the exit () function, because once the exit () function is used, it is actually the exit of the entire process, causing other threads to die as the process dies waiting for the thread to exit
After the thread has been created, the thread that created the thread can use the Pthread_join () function to wait for the end of the thread being created. The Pthread_join () function suspends execution of the thread that created the thread until it waits to the child thread that wants to wait
Function Prototypes:
int Pthread_join (pthread_t th, void **thread_return);
The first argument th is the flag of the thread that needs to wait
If the Thread_return is not empty, then the Thread_return point to the th return value
The purpose of calling the Pthread_join () function is to release the associated memory resource thread detach
Enables the child thread itself to have the ability to reclaim memory resources
Function Prototypes:
int Pthread_detach (pthread_t th);
The purpose of this function is to allow thread th to be in a detached (detached) state
Threads in a detached state have the ability to reclaim related memory resources at the end of their execution
Current thread flag
Use the Pthread_self () function to get the flags for the current thread
Function Prototypes:
pthread_t pthread_self (void); Undo of Threads
One thread can end execution of another thread by sending a "request" to another thread. The Pthread_cancel () function can complete this function.
Function Prototypes:
Pthread_cancel (pthread_t thread)
The current thread will kill the thread with thread ID as thread
Pthread_exit () is the current thread has its own exit, and Pthread_cancel is another thread that kills another threadImplementation Code

Bug
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include < pthread.h>

void *helloworld (void *arg)
{
    int i=1;
    while (1)
    {
        printf ("==hello==");
        if (i==3) {
            //thread exits 1
            pthread_exit (NULL);
        }
        Exits the entire * * * * *
        exit (0);
    }
    Thread exits 2 return
    NULL;
}

int main (int argc, char *argv)
{
    int i;
    pthread_t Tid;
    Threads Create
    if (pthread_create (&tid, NULL, Helloworld, NULL)!= 0) {
        printf ("==fail = =");
        return-1;
    }
    printf ("==main==");
    For (I=1 i<5; i++)
    {
        printf ("!==main==");
    }
    return 0;

Steps
1. Create the. c File #touch m_pthread.c
2. Edit #vi M_PTHREAD.C
3. Link #gcc-o Fred M_pthread.c-lpthread
4. Executive #./fred

The use of Pthread line threading
The glib library has a built-in line threading.
Use header file in source code pthread.h
Link with GCC with –lpthread option, link wiring threading thread Mutex (mutex)

synchronization and Mutex differences:
synchronization: One execution, the other corresponding (executed together)
Mutual exclusion: One execution, and the other waiting for it to execute to perform (single single execution) a mutex role: used to protect shared data structures in concurrent read and write operations, which can actually be used by mutexes to implement critical code areas with only locked and unlocked states

Characteristics:
Atomicity: One thread carries out a mutex operation, others cannot operate on the same mutex
Singleness: A thread that owns a mutex unless it is freed, other threads cannot have
Not busy waiting: Wait for unlock to use this mutex

Mutex basic functions
Deadlock: Stop at a place that doesn't run
int Pthread_mutex_init
int Pthread_mutex_lock
int Pthread_mutex_trylock
int Pthread_mutex_unlock
int Pthread_mutex_destroy synchronization of Threads

A condition variable is a synchronization device for a thread
-Basic functions
pthread_cond_t cond= Pthread_cond_initializer;
int Pthread_cond_init Initialization Condition variable
int pthread_cond_signal A thread that starts waiting for cond to point to a condition variable
int Pthread_cond_broadcast The thread that starts all the waiting condition variables
The int pthread_cond_wait unlocks the mutex that its second argument points to, and then waits for the conditional variable to satisfy
int pthread_cond_timedwait wait for the condition to be satisfied within the specified time
int pthread_cond_wait Infinite Wait
int Pthread_cond_destroy The amount of resource semaphore that the conditional variable is released from

POSIX semaphores can play a synchronous or mutually exclusive role in multithreaded programming. Traditional operating system P (through), V (release) operations can be implemented with POSIX semaphore

The operating functions for POSIX semaphores are:
int Sem_init Initialization semaphore
int sem_wait blocking execution of current thread
int sem_trywait
int Sem_post sem points to the semaphore count plus 1, which corresponds to V operation
int Sem_getvalue Gets the current semaphore value
int Sem_destroy Free Semaphore resource

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.