线程执行顺序之一
一般情況下,線程在主函數創建,函數分配在棧區,遵循先進后出規則,先創建后運行
#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;
?? ?
?? ?//創建兩個線程
?? ?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;
}
?
總結
- 上一篇: Linux的进程/线程间通信方式总结
- 下一篇: _T