线程执行顺序之一
一般情況下,線程在主函數(shù)創(chuàng)建,函數(shù)分配在棧區(qū),遵循先進后出規(guī)則,先創(chuàng)建后運行
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
?
int var ?= 8;
?
void *thread_1(void *arg)
{
?? ?while(1)
?? ?{
?? ??? ?printf("this is my new thread1: var++\n");
?? ??? ?var++;
?? ??? ?sleep(1);
?? ?}
?? ?return NULL;
}
?
void *thread_2(void * arg)
{
?? ?while(1){
?? ??? ?printf("this is my new thread2: var = %d\n", var);
?? ??? ?sleep(1);
?? ?}
?? ?
?? ?return NULL;
}
?
int main(int argc, char *argv[])
{
?? ?pthread_t tid1,tid2;
?? ?
?? ?//創(chuàng)建兩個線程
?? ?pthread_create(&tid1, NULL, thread_1, NULL); ?
?? ?pthread_create(&tid2, NULL, thread_2, NULL);
?? ?
?? ?while(1){
?? ??? ?printf("the main thread: var = %d\n", var);
?? ??? ?sleep(1);
?? ?}
?? ?
?? ?return 0;
}
?
總結(jié)
- 上一篇: Linux的进程/线程间通信方式总结
- 下一篇: _T