以下代码实现了用C语言在控制台实现了创建两个线程,各自线程中对对应的全局变量进行叠加操作。
注意:
以下代码不能在gcc6.3.0中编译,否则会报错:more_thread.c:3:21: fatal error: pthread.h: No such file or directory。
在gcc13.2.0中可以正常编译执行。
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int count1 = 0;
int count2 = 0;
void *thread_func1(void* arg)
{
while(1)
{
sleep(1);//sleep 1s
count1++;
printf("thread1 count1[%d]\r\n", count1);
}
return;
}
void *thread_func2(void* arg)
{
while(1)
{
usleep(500000);//sleep 500ms
count2++;
printf("thread2 count2[%d]\r\n", count2);
}
return;
}
int main()
{
pthread_t thread1;
pthread_t thread2;
//creat thread
pthread_create(&thread1, NULL, thread_func1, NULL);
pthread_create(&thread2, NULL, thread_func2, NULL);
while(1)
{
printf("count1 [%d], count2 [%d]\r\n", count1, count2);
sleep(1);
}
return 0;
}