Line program control system (Linux C) __linux

Source: Internet
Author: User
Tags mutex

The thread is the smallest unit that runs independently in the computer, the running resource is very small, the macroscopic on-line process executes simultaneously. Micro-CPU control by allocating time slices through the system alternately executes the code in the thread. Of course, multi-core situations can be parallel. directory thread benefits thread-private data-thread synchronization method

Advantages of threads

1. Save resources and save time. When multiple processes are in progress, each process has its own space, and the address space of a multithreaded shared process under the same process. It also saves the time it takes to allocate space for it.

2. Because the address space is shared, the switching speed between threads is much faster than the process.

3. Thread sharing space, communication more convenient.

Private data

1. Thread ID. Unique identification, basic call to close the teleportation signal is all used by it.

2. Registers. Includes program counters and stack pointers.

3. Stack.

4. Signal mask.

Priority level.

Thread-Private storage space

Thread-Private data can be accessed by functions within a thread, but is blocked for other threads.
Thread-private data is a key-multivalued technique that accesses data by key values, as if accessing a variable is actually accessing different data, so before using private data, create an associated key for each thread.

Test code:

#include <stdio.h>
#include <string.h>
#include <pthread.h>
pthread_key_t key;
void *thread2 (void *arg)
{
    int tsd = 5;
    printf ("Thread%d is running\n", pthread_self ());
    Pthread_setspecific (Key, (void *) TSD);
    printf ("Thread%d return%d\n", Pthread_self (), pthread_getspecific (key));
void *thread1 (void *arg)
{
    int tsd = 0;
    pthread_t Thid2;
    printf ("Thread%d is running\n", pthread_self ());
    Pthread_setspecific (Key, (void *) TSD);
    Pthread_create (&thid2, NULL, thread2, NULL);
    Sleep (2);
    printf ("Thread%d return%d\n", Pthread_self (), pthread_getspecific (key));
int main (int argc, char *argv)
{
    pthread_t thid1;
    printf ("Main thread begigs running\n");
    Pthread_key_create (&key, NULL);  
    Pthread_create (&THID1, NULL, THREAD1, NULL);
    Sleep (3);
    Pthread_key_delete (key);
    printf ("Main thread exit\n");
    return 0;
}

Main functions:

Assign an item from the TSD pool to assign the value to key,destr_function as the scavenging function
 int pthread_key_create (pthread_key_t *key, Void (*destr_function) ( void *));

 The value of the pointer is associated with the key
 int pthread_setspecific (pthread_key_t key, const void *pointer);

The Data
void *pthread_getsspecific (pthread_key_t key) associated with the key is obtained.

Used to remove the key, release the memory of the key occupied by
 int pthread_key_delete (pthread_key_t key);

Run Result:

Code, the main function creates thread 1, thread 1 creates thread 2, they share the global variable key as the key value, but the private data TSD different. The main function is that the thread internal function pthread_setspecific (key, TSB) associates the key key with the TSB value to achieve a key multivalued value.

Thread creation

Sometimes the control thread is required to execute only once, and the following code attempts to implement this requirement.

#include <stdio.h>
#include <pthread.h>
pthread_once_t once = Pthread_once_init;
void run (void)
{
    printf ("Function run is running in thread%u\n",                                                            pthread_self ());   The Pthread_self () function gets the current thread's ID
}
void *thread1 (void *arg)
{
    printf ("The present thread ' s ID is%u\n"). Pthread_self ());
    Pthread_once (&once, run);  This function is used to guarantee that the function performs one
    printf ("Thread1 ends\n");
}
void *thread2 (void *arg)
{
    printf ("Current thread ' s ID is%u\n", pthread_self ());
    Pthread_once (&once, run);
    printf ("Thread2 end\n");
}
int main ()
{
    pthread_t thid1, Thid2;
    Pthread_create (&THID1, NULL, THREAD1, NULL); 
    Pthread_create (&thid2, NULL, thread2, NULL);
    Sleep (3);
    printf ("Main thread exit!\n");
    Exit (0);
}

Run Result:

You can see the function run ... For once.

Thread synchronization

The most important feature of threads is synchronicity. But the problem of resource allocation becomes difficult when synchronizing. Linux provides mutexes, conditional variables, and asynchronous signals to handle this problem.

Mutual exclusion Lock

The use of the lock is simple, the use of pthread_mutex_init () initialization of a mutex can be used, the following methods:

Pthread mutex_t Number_mutex;   Mutual-exclusion lock
Pthread_mutex_lock (&number_mutex);  Lock
Globalnumber + +;    A global variable
pthread_mutex_unlock (&number_mutex);  Unlock

When using Pthread_mutex_lock () lock, other threads do not have access to the entire variable, unless it is unlocked.

Let's look at a couple of related functions:
Pthread_mutex_init (); Initializing a mutual exclusion lock
Pthread_mutex_destroy (); Unregister a mutex
Pthread_mutex_lock (); Lock, if not successful, block wait
Pthread_mutex_unlock (); Unlock
Pthread_mutex_trylock (); Try locking. If you do not succeed immediately return, the error code is EBUSY

Condition variable

The condition variable is similar to the IF statement on the macroscopic level, and can execute a certain procedure if it meets the condition, otherwise it can only wait for the condition.
Using a conditional variable consists of two actions, a thread waiting to use the resource waits for the condition variable to be set to true, and the other thread sets the condition to true when the resource is exhausted.
Conditional variables are generally used in conjunction with mutex locks.

Main functions:

Pthread_cond_init ();   Initialize the condition variable
pthread_cond_wait ();  Based on conditional variable blocking, unconditional waiting for
pthread_cond_timewait ();  Block until time occurs, timed to wait for
pthread_cond_signal ();//Resolve specific thread waiting
pthread_cond_broadcast ();  Unblock all threads from blocking
pthread_cond_destory ();   Clear the condition variable

Asynchronous signal

The signal is asynchronous with any thread, that is, the time when the signal arrives at the thread is variable,
Functions to handle asynchronous signals:

Sends a signal to the thread threadid signo
int Pthread_kill (pthread_t threadid, int signo);

Set the thread's signal mask
int pthread_sigmask (int how, const sigset_t *newmask, sigset_t *oldmask);

Blocks a thread, waits for a signal in the set to arrive, and deposits it in *sig
int sigwait (const sigset_t *set, int *sig);

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.