linux--Programming--Thread __HTML5

Source: Internet
Author: User
Tags mutex semaphore stdin
problem arises:

Switching between processes requires a large, long time to find a better way to appear in threads.

The difference between a new process and a new thread: The new process has its own PID, variable, time independent, and execution independent. The new thread has its own stack (that is, it has its own local variables), but it shares the PID with the creator, global variables, signal processing functions, current directory state, and so on. Thread Process:

You must define a macro _reentrant and rely on the Pthread.h header file, and use the-lpthread option at compile time. Thread Properties:

The two most important are:

#include <pthread.h>
int pthreed_attr_init (pthread_attr_t *attr);
int Pthread_attr_destroy (PTHREAD_ATTR_T*ATTR);

There are others, their own Baidu, through a variety of thread property functions can be set such as graduation, thread scheduling and so on.

code example:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> void *thread_

function (void *arg);
Char message[] = "Hello World";

int thread_finished = 0;
    int main () {int res;
    pthread_t A_thread;
    void *thread_result;

    pthread_attr_t thread_attr;
        res = Pthread_attr_init (&thread_attr);//Property Initializes if (res!= 0) {perror ("Attribute creation failed");
    Exit (Exit_failure);
        res = Pthread_attr_setdetachstate (&thread_attr, pthread_create_detached);//allow the thread to be merged without merging if (res!= 0) {
        Perror ("Setting detached attribute failed");
    Exit (Exit_failure);
    }//Create thread res = pthread_create (&a_thread, &thread_attr, thread_function, (void *) message);
        if (res!= 0) {perror ("Thread creation failed");
    Exit (Exit_failure); } (void) Pthread_attr_destroy (&thread_attr);//Property Cleanup Recycle while (!thread_finished) {printf ("Waiting for thre Ad to say it ' s finisheD...\n ");
    Sleep (1);
    printf ("Other thread finished, bye!\n");
Exit (exit_success); }//thread function void *thread_function (void *arg) {printf ("Thread_function is running.")
    Argument was%s\n ", (char *) arg);
    Sleep (4);
    printf ("Second thread setting finished flag, and exiting now\n");
    thread_finished = 1;
Pthread_exit (NULL); }

Threading Process To create a thread:

#include <pthread.h>
int pthread_creat (pthread_t*thread,pthread_attr_t *attr,void * (*start_routine) (void *), void *arg);

Parameter 1: When a thread is created, the variable that the pointer points to will be written to an identifier to reference the new thread.

Parameter 2: Used to set thread properties. Null can be set if no special attributes are required.

Parameter 3: Pass the thread function ontology.

Parameter 4: Pass the thread function arguments.

Return value: Successfully returned 0, error return error code.

Take a look at the thread function: void*thread_function (void *arg);/note here the void * waits for the thread:

#include <pthread.h>
int pthread_join (pthread-t th,void **thread_return);

Parameter 1: The thread to wait, the return identifier for the first parameter of Pthread_creat.

Parameter 2: A two-level pointer that eventually points to the return value of a thread.

Return value: Successfully returned 0, error return error code.

Note: If you do not have this function in your program, the main program will end quickly, causing the thread to end without having time to begin. This function is essentially the end of the thread specified by blocking wait thread to finally reclaim the thread resource. Different from the function is another thread----detach from the thread.

This can be used for a level two pointer:

void *thread_result;
res = Pthread_join (a_thread,&thread_result);

Terminate thread:

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

To cancel a thread:

#include <pthread.h>
int pthread_cancle (pthread_t thread);//Very simple, no more say
int pthread_setcanclestate (int STAT,INT*OLDSTAT);

Parameter 1: The value can be pthread_cancle_enable, which allows the thread to receive a cancellation request. The value can also be pthread_cancle_disable, which is to ignore cancellation requests.

Parameter 2: Used to get the previous cancellation state, if you do not want to use the can be set to null.

int pthread_setcancletype (int type,int*oldtype);

Parameter 1: The value can be pthread_cancle_asynchronous, the function is to receive cancellation request immediately after execution, can also be pthread_cancle_defereed, the role is not immediately executed, Action is not taken until the following function is performed: Pthread_join, pthread_cond_wait, pthread_cond_timedwait, Pthread_testcancle, sem_wait, or sigwait.

Parameter 2: Used to get the previous cancellation state, if you do not want to use the can be set to null. By default, a thread is pthread_cancle_enable at startup and the type is pthread_cancle_defreed. code Example:

1. Code with no cancellation thread:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <

pthread.h> void *thread_function (void *arg);

Char message[] = "Hello World";
    int main () {int res;
    pthread_t A_thread;
    void *thread_result; res = Pthread_create (&a_thread, NULL, thread_function, (void *) message)//Create thread if (res!= 0) {perror ("Thr
        EAD creation failed ");
    Exit (Exit_failure);
    printf ("Waiting for Thread to finish...\n");
        res = Pthread_join (A_thread, &thread_result);//wait thread if (res!= 0) {perror ("thread join failed");
    Exit (Exit_failure);
    printf ("Thread joined, it returned%s\n", (char *) thread_result);
    printf ("Message being now%s\n", message);
Exit (exit_success); } void *thread_function (void *arg) {printf ("Thread_function is running.
    Argument was%s\n ", (char *) arg);
    Sleep (3);
    strcpy (Message, "bye!"); Pthread_exit ("Thank for the CPU time");Exit Thread} 

2, with the cancellation of the thread code:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <pthread.h> void *thread_

function (void *arg);
    int main () {int res;
    pthread_t A_thread;

    void *thread_result; res = pthread_create (&a_thread, NULL, thread_function, NULL);//Create Thread if (res!= 0) {perror ("thread Creatio
        N Failed ");
    Exit (Exit_failure);
    Sleep (3);
    printf ("Canceling thread...\n");
        res = Pthread_cancel (a_thread);//Cancel the implementation of the thread if (res!= 0) {perror ("thread cancelation failed");
    Exit (Exit_failure);
    printf ("Waiting for Thread to finish...\n");
        res = Pthread_join (A_thread, &thread_result);//wait thread if (res!= 0) {perror ("thread join failed");
    Exit (Exit_failure);
} exit (exit_success);
    }//thread function void *thread_function (void *arg) {int I, res, J; res = Pthread_setcancelstate (pthread_cancel_enable, NULL);/Set Cancel Property state if (res!= 0) {perror ("Thread pthread_se TcaNcelstate failed ");
    Exit (Exit_failure); res = Pthread_setcanceltype (pthread_cancel_deferred, NULL);/Set Cancel property type if (res!= 0) {perror ("Thread PTH
        Read_setcanceltype failed ");
    Exit (Exit_failure);
    printf ("Thread_function is running\n");
        for (i = 0; i < i++) {printf ("The Thread is still running (%d) ... \ n", i);
    Sleep (1); } pthread_exit (0);//Exit Thread}

thread synchronization:

Signal Volume

Similar to the only door inspector

#include <semaphore.h>
//initialization semaphore
int sem_init (sem_t *sem,intpshared,unsigned int value);
Control semaphore
int sem_wait (sem_t * sem);//similar to P atomic operation, -1
int sem_post (sem_t * sem);//similar to v atomic operation, +1
/clear Semaphore
int Sem_destroy (sem_t * sem);

Sem_init () function parameter explanation:

Parameter 1: The semaphore pointer to point to.

Parameter 2: Control semaphore type, a value of 0 indicates that the semaphore is the local semaphore of the current process, otherwise this semaphore can be shared among multiple processes.

All functions successfully returned 0.

code example:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <
pthread.h> #include <semaphore.h> void *thread_function (void *arg);

Sem_t Bin_sem;

#define WORK_SIZE 1024 char work_area[work_size];
    int main () {int res;
    pthread_t A_thread;

    void *thread_result;
    res = sem_init (&bin_sem, 0, 0);
        if (res!= 0) {perror ("semaphore initialization failed");
    Exit (Exit_failure);
    res = pthread_create (&a_thread, NULL, thread_function, NULL);
        if (res!= 0) {perror ("Thread creation failed");
    Exit (Exit_failure); printf ("Input some text.")
    Enter ' End ' to finish\n ');
        while (STRNCMP ("End", Work_area, 3)!= 0) {fgets (Work_area, Work_size, stdin);
    Sem_post (&bin_sem);
    printf ("\nwaiting for Thread to finish...\n");
    res = Pthread_join (A_thread, &thread_result);
    if (res!= 0) {perror ("Thread join failed");    Exit (Exit_failure);
    printf ("Thread joined\n");
    Sem_destroy (&bin_sem);
Exit (exit_success);
    } void *thread_function (void *arg) {sem_wait (&bin_sem);
        while (strncmp (' End ', Work_area, 3)!= 0) {printf ("You input%d characters\n", strlen (Work_area)-1);
    Sem_wait (&bin_sem);
} pthread_exit (NULL); }

Mutex Amount

Like the only security guard at the door.

#include <pthread.h>
//initialization semaphore
int Pthread_mutex_init (Pthread_mutex_t*mutex,const pthread_mutexattr_ T *mutexattr);
Lock resource
int pthread_mutex_lock (PTHREAD_MUTEX_T*MUTEX);
Unlock resource
int pthread_mutex_unlock (PTHREAD_MUTEX_T*MUTEX);
Clearing the semaphore
int Pthread_mutex_destroy (PTHREAD_MUTEX_T*MUTEX);

Pthread_mutex_init () function parameter explanation:

Parameter 1: The semaphore pointer to point to.

Parameter 2: Here slightly off, own Baidu.

All functions return 0 successfully, failure returns an error code, but these functions do not set an error.

code example:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <
pthread.h> #include <semaphore.h> void *thread_function (void *arg); pthread_mutex_t Work_mutex;
/* protects both Work_area and time_to_exit */#define WORK_SIZE 1024 char work_area[work_size];

int time_to_exit = 0;
    int main () {int res;
    pthread_t A_thread;
    void *thread_result;
    res = Pthread_mutex_init (&work_mutex, NULL);
        if (res!= 0) {perror ("Mutex initialization Failed");
    Exit (Exit_failure);
    res = pthread_create (&a_thread, NULL, thread_function, NULL);
        if (res!= 0) {perror ("Thread creation failed");
    Exit (Exit_failure);
    } pthread_mutex_lock (&work_mutex); printf ("Input some text.")
    Enter ' End ' to finish\n ');
        while (!time_to_exit) {fgets (Work_area, Work_size, stdin);
        Pthread_mutex_unlock (&work_mutex); while (1) {Pthread_mutex_loCK (&work_mutex);
                if (work_area[0]!= ' ") {Pthread_mutex_unlock (&work_mutex);
            Sleep (1);
            } else {break;
    }} pthread_mutex_unlock (&work_mutex);
    printf ("\nwaiting for Thread to finish...\n");
    res = Pthread_join (A_thread, &thread_result);
        if (res!= 0) {perror ("Thread join failed");
    Exit (Exit_failure);
    printf ("Thread joined\n");
    Pthread_mutex_destroy (&work_mutex);
Exit (exit_success);
    } void *thread_function (void *arg) {sleep (1);
    Pthread_mutex_lock (&work_mutex);
        while (strncmp (' End ', Work_area, 3)!= 0) {printf ("You input%d characters\n", strlen (Work_area)-1);
        Work_area[0] = ' the ';
        Pthread_mutex_unlock (&work_mutex);
        Sleep (1);
        Pthread_mutex_lock (&work_mutex); while (work_area[0] = = ' = ') {Pthread_mutex_unlock (&work_mutex);
            Sleep (1);
        Pthread_mutex_lock (&work_mutex);
    } time_to_exit = 1;
    Work_area[0] = ' the ';
    Pthread_mutex_unlock (&work_mutex);
Pthread_exit (0); }
Problem Resolution: Multithreaded code example:

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <

pthread.h> #define Num_threads 6 void *thread_function (void *arg);
  int main () {int res;
  pthread_t A_thread[num_threads];
  void *thread_result;
  

  int lots_of_threads; for (lots_of_threads = 0; lots_of_threads < num_threads; lots_of_threads++) {res = Pthread_create (& a_thread[l
    Ots_of_threads]), NULL, thread_function, (void *) lots_of_threads);
      if (res!= 0) {perror ("Thread creation failed");
    Exit (Exit_failure); }/* Sleep (1);
  */} printf ("Waiting for Threads to finish...\n"); for (lots_of_threads = num_threads-1; lots_of_threads >= 0; lots_of_threads--) {res = Pthread_join (a_thread[lots_
    Of_threads], &thread_result);
    if (res = = 0) {printf ("picked up a thread\n");
    else {perror ("Pthread_join failed");
  
  } printf ("All done\n");
Exit (exit_success); } void *threaD_function (void *arg) {int my_number = (int) arg;

    int rand_num; printf ("Thread_function is running.
    Argument was%d\n ", my_number);
    rand_num=1+ (int) (9.0*rand ()/(rand_max+1.0));
    Sleep (Rand_num);
    
    printf ("Bye from%d\n", my_number);
Pthread_exit (NULL); }

Reference Documentation:

Linux Programming Fourth edition people posts and Telecommunications press

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.