Thread: A thread is created in a process, and its life cycle is in this process.
Thread: it allows a process to execute one or more execution paths (that is, a process can have multiple threads to execute different programs). These execution paths are asynchronously scheduled by the system.
A process has its own data segment, code segment, and stack segment.
The difference between threads and processes:
1. The same code segment
2. data segments are the same (global variables ).
3. Stack heap segments are different !!!!!
Function used to create a thread:
# Include <pthread. h>
Int pthread_create (pthread_t * thread, pthread_attr_t * ATTR,
Void * (* start_routine) (void * Arg ),
Void * Arg );
Function: Creates a thread.
Return Value: Success 0
Thread: The program id (identifier ).
ATTR: Specifies the thread attributes. If it is null, the default thread attribute is created.
Start_routine: the starting address of the thread-running function.
The last parameter is the parameter of the thread-running function.
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 pthid.
// If ATTR is null, the default attributes shall be used.
// If the second parameter is null, a process with the default attribute is created.
//... 3 .. The starting address of the thread-running function,
// ...... The parameters of the thread running function.
If (Ret! = 1 ){
Perror ("can't creat thread ");
Exit (exit_failure );
}
Printf ("main thread! \ N ");
Sleep (1 );
Exit (0); // return 0;
}
Running result:
The following is an example:
# Include <stdio. h>
# Include <stdlib. h>
# Include <pthread. h>
Void * th_fun (void * Arg)
{
Printf ("% s", ARG); // print the passed Parameter
While (1)
Fputs ("New thread \ n", 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 \ n", stdout );
// Output string main thread to standard output
Return 0;
}
Running result:
From the running result, it will output main thread and new thread.
We can see that the System Schedules two threads.