Thread: is created in a process, and it reaches the lifecycle of the process.
Thread it allows a process to execute one or more execution paths (that is, 1 processes can have multiple threads to execute different programs), and these execution paths are scheduled asynchronously by the system.
The process has its own data segment, code snippet, stack segment.
And the difference between threads and processes:
1. Same Code snippet
2. The same data segment (global variable).
3. Stack segment is not the same!!!!!
To create a thread's function:
#include <pthread.h>
int Pthread_create (pthread_t*thread,pthread_attr_t *attr,
void * (*start_routine) (void *arg),
void *arg);
Features: Creating Threads
Return value: Success 0
Thread: The ID (identifier) of the program.
attr: The properties of the thread are set, and if NULL, the system default thread properties are created.
Start_routine: The starting address where the thread runs the function.
The last parameter is a parameter that runs the function by the thread.
Example:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *thfun (void *arg)
{printf ("New thread!\n");
printf ("%s\n", (char*) arg);
return ((void *) 0);
}
int main (int argc, char *argv[])
{
int ret;
pthread_t Pthid;
Ret=pthread_create (&pthid,null,thfun, (void *) "Hello");
The first parameter is the thread ID, which is saved in the Pthid.
If attr is NULL, the default attributes shall to be used.
If the second argument is null, the process that creates the default property.
。。。 3.. The start address of the thread running function,
//..... 4.. threads run the parameters of the function.
If (ret!=1) {
Perror ("Can ' tcreat thread");
Exit (Exit_failure);
}
printf ("Main thread!\n");
Sleep (1);
Exit (0);//return 0;
}
Run Result:
Let's take a look at the following example:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *th_fun (Void*arg)
{
printf ("%s", arg);//Print Pass Parameters
while (1)
Fputs ("New thread \ \", stdout);
Output string new thread to standard output
Return ((void*) 0);
}
int main ()
{
int ret;
pthread_t Tid;
if ((Ret=pthread_create (&tid,null,th_fun, "New Thread created!\n") ==-1)
{
Perror ("Pthread_createerror");
Exit (Exit_failure);
}
while (1)
Fputs ("main thread \ \", stdout);
Output string main thread to standard output
return 0;
}
Run Result:
We see from the results of the operation that it will output the main thread one at a while output new thread
It can be seen that the system is scheduled for two threads.