Linux Threads Basic use Code Demo sample

Source: Internet
Author: User

#include <pthread.h> #include <stdio.h> #include <unistd.h>void* thread_func (void* param) {const char    * p = (const char*) param;    pid_t pid = 0;    pthread_t tid = 0;    PID = Getpid ();    Tid = Pthread_self (); printf ("%s-%8u%8u\n", p, (unsigned int) PID, (unsigned int) tid);}    void* thread_wait_cancel (void* p) {printf ("Thread wait Cancel, I ' M waitting for cancel\n");    Sleep (10000); printf ("If u saw me, there got be something wrong\n");}    int main (int argc, char* argv[]) {pthread_t tid = 0;        Pthread_create (&tid, NULL, Thread_func, (void *) "sub thread");    pthread_t tid_cancel = 0;    Pthread_create (&tid_cancel, NULL, thread_wait_cancel, NULL);        Wait thread tid to exit Pthread_join (Tid, NULL);    Cancel a thread void* stat = 0;    Pthread_cancel (Tid_cancel);    Pthread_join (Tid_cancel, &stat);    /* Stat =-1 stand for pthread_canceled */printf ("Cancel thread exit State:%d\n", stat); Show Main ThreaD infomation Thread_func (void *) "main thread"); return 0;}



Note that you need to add the option-lpthread when compiling. Because Pthread is not the default library for Linu, as seen in the following:

GCC Thr.c-lpthread


Linux Threads Basic use Code Demo sample

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.