Linux multithreaded Practice (2)--Thread Basic API

Source: Internet
Author: User
Tags posix usleep

POSIX line Libraries

Thread-related functions constitute a complete series, most of the names of the functions begin with "Pthread_", to use these libraries, by introducing header <pthread.h>, and to use the "-lpthread" of the compiler command when linking these thread libraries Options [Ubuntu Series system needs to add "-pthread" option instead of "-lpthread", such as Ubuntu 14.04 version, Deepin Ubuntu etc.]

Pthread_create

Create a new thread

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

Parameters:

Thread: Threads ID

attr: Setting the properties of a thread, attr null means using the default property

Start_routine: is a function address, the function to execute after the thread starts

ARG: Arguments passed to the thread start function

Return value: Successful return 0, failure return error code

Attach-Error Checking

UNIX Traditional functions: Successfully returned 0, failed to return 1, and set global variable errno to specify the error type. However, the Pthreads function does not set the global variable errno (while most of the other POSIX functions will set the errno). Instead, the error code is returned by the return value;

Pthreads also provides errno variables within the thread to support other code that uses errno. For errors in the Pthreads function, it is recommended that the return value be determined because reading the return value is less expensive than reading the errno variable inside the thread !

Practice # include <iostream> #include <errno.h> #include <unistd.h> #include <pthread.h> #include <string.h> #include <stdio.h> #include <stdlib.h>using namespace std;void *thread_routine (void *args {for    (int i = 0; i <; ++i)    {        printf ("A");        Fflush (stdout);        Usleep ();    }    return 0;} int main () {    pthread_t tid;    int ret = 0;    if (ret = Pthread_create (&tid,null, Thread_routine,null), NULL)! = 0)    {        fprintf (stderr, "%s\n", strerror (ret));        Exit ( -1);    }    for (int i = 0; i <; ++i)    {        printf ("B");        Fflush (stdout);        Usleep ();    }    cout << Endl;    Pthread_join (tid,null);//The function below will be encountered: Wait for thread to end}


Run the results (you can see that the threads are running alternately and running differently):



Pthread_exit

Thread termination

void Pthread_exit (void *value_ptr);

Parameters:

Value_ptr: Point to the return value of the thread; Note: value_ptr cannot point to a local variable .

Pthread_join

Wait for thread to end

int Pthread_join (pthread_t thread, void **value_ptr);

Parameters:

Thread: Threads ID

Value_ptr: It points to a pointer, which points to the return value of the thread (the return value of the user gets the thread)

Return value: Successful return 0, failure return error code


practice void *threadfunction (void *args) {    cout << "Start Thread ..." << Endl;    cout << "End Thread ..." << Endl;    Pthread_exit (NULL);} int main () {    pthread_t thread;    Start Create and start thread    pthread_create (&thread,null,threadfunction,null);    cout << "Main Running ..." << Endl;    cout << "Main ending ..." << Endl;    Wait for thread to end    Pthread_join (thread,null);    return 0;}


Pthread_self

Return thread ID

pthread_t pthread_self (void);D escriptionthe pthread_self () function shall return the thread ID  of the Calling thread.

Practice 1:void *thread_routine (void *args) {cout << pthread_self () << "START ..." << Endl;        for (int i = 0; i <; ++i) {printf ("A");        Fflush (stdout);    Usleep (20);    } sleep (3);    cout << pthread_self () << "END ..." << Endl;    Pthread_exit (Const_cast<char *> ("Thread_routine exit"); return (void *) "EDF";    int main () {pthread_t tid;    int ret = 0; if (ret = Pthread_create (&tid,null, Thread_routine,null), NULL)! = 0) {fprintf (stderr, "Pthread_create:%s\n        ", Strerror (ret));    Exit (Exit_failure);        } for (int i = 0; i <; ++i) {printf ("B");        Fflush (stdout);    Usleep (20);    } cout << Endl;    void *threadvalue;        if (ret = Pthread_join (tid,&threadvalue))! = 0) {fprintf (stderr, "Pthread_join:%s\n", strerror (ret));    Exit (Exit_failure); } cout << "return message:" << Static_cast<char *> (threadvalue) << Endl;} 


Practice 2: The master thread and the child thread pass data typedef struct _student{    char name[20];    unsigned int age;} Student;void *threadfunction (void *args) {    cout << "in Thread:" << pthread_self () << Endl;    Student tmp = * (Student *) (args);    cout << "Name:" << tmp.name << Endl;    cout << "Age:" << tmp.age << Endl;    Pthread_exit (NULL);} int main () {    Student Student = {"Xiaofang", +};    pthread_t thread;    Start Create and start thread    pthread_create (&thread,null,threadfunction,&student);    Wait for thread to end    Pthread_join (thread,null);    return 0;}



Pthread_cancel

To cancel a thread in execution

int Pthread_cancel (pthread_t thread);

Return value: Successful return 0, failure return error code;

Pthread_detach

Detach a thread-if the main thread does not end at the end of the newly created threads and does not call Pthread_join, a zombie thread is generated, and the second problem can be resolved by setting the thread as detached (detach);

int Pthread_detach (pthread_t thread);

Return value: Successful return 0, failure return error code;

Summary: Process VS. Thread

Process (pid_t)

Thread (pthread_t)

Fork

Pthread_create

Waitpit

Pthread_join/pthread_detach

Kill

Pthread_cancel

Pid

Pthead_self

Exit/return

Pthread_exit/return


Linux multithreaded Practice (2)--Thread Basic API

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.