C + + class inside some thread functions

Source: Internet
Author: User

In the development of multithreading, many examples on the internet are to write the thread function as a global function, but if you want to write a threading operation into a class, the thread function is placed inside the class, and if you have a problem with a normal class function, because the thread function passed in in the API that invokes the create thread needs to be fixed at compile time, If you are a normal class function, you cannot determine the address at compile time, you need to create an object of the class to get it. So, if you want to write the execution function of a thread as a static function, or a global function, you can determine the function address at compile time.

Cases:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>


Class Cthread
{
Private
int ThreadRun ();//Thread execution function
static int count;
pthread_t pid;
Public
int start ();//thread Start
Static void* ThreadFunc (void *arg);//static function, thread function
};

int cthread::count = 0;

int Cthread::threadrun ()
{
while (1)
{
Sleep (1);
printf ("aaaaaaaaaa-----%d\n", ++count);
}
return 0;
}

int Cthread::start ()
{

pthread_t Tid;
Pthread_create (&tid, NULL, ThreadFunc, (void*) this);
return 0;
}

void* cthread::threadfunc (void *arg)
{
Cthread *obj = (cthread*) arg;
Obj->threadrun ();
}


int main (int argc, char **argv)
{
Cthread obj;
Obj.start ();
Sleep (20);
return 0;
}



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.