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;
}