Linux应用编程—5.多线程的创建以及线程间数据共享
5.1 多线程的创建
创建多线程,则多次调用pthread_create()函数。创建两个线程,线程1每隔一秒打印字符串:Hello world!,线程2每隔一秒打印字符串:Good moring!编写代码如下:
include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void * pthread1_function(void *arg);
void * pthread2_function(void *arg);
int main(void)
{
pthread_t pthread_1, pthread_2;
int ret = 0;
ret |= pthread_create(&pthread_1, NULL, pthread1_function, NULL);
if(0 != ret)
{
perror("pthread create.");
exit(1);
}
ret |= pthread_create(&pthread_2, NULL, pthread2_function, NULL);
if(0 != ret)
{
perror("pthread create.");
exit(1);
}
pthread_join(pthread_1, NULL);
pthread_join(pthread_2, NULL);
return 0;
}
void * pthread1_function(void *arg)
{
printf("Pthread1 start running.\n");
while(1)
{
printf("Hello world!\n");
sleep(1);
}
return NULL;
}
void * pthread2_function(void *arg)
{
printf("Pthread2 start running.\n");
while(1)
{
printf("Good moring.\n");
sleep(1);
}
return NULL;
}
运行结果:
Pthread1 start running.
Hello world!
Pthread2 start running.
Good moring.
Hello world!
Good moring.
Hello world!
Good moring.
Good moring.
Hello world!
Hello world!
Good moring.
Good moring.
Hello world!
Hello world!
Good moring.
Good moring.
Hello world!
Hello world!
Good moring.
Good moring.
Hello world!
Hello world!
Good moring.
^C
可以看出两个线程内的代码同时运行,看上去Hello world!与Good moring.每隔一秒,同时打印出来。
5.2 多线程之间数据共享
定义一个全局变量,分别在两个线程中对其进行++操作以及打印结果。回顾之前父子进程对同一个变量的操作,父子进程在内存中是互相独立的,所以,他们分别增加,两者互相不影响。编写代码测试在线程中对一个全局变量的操作会有什么现象。
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void * pthread1_function(void *arg);
void * pthread2_function(void *arg);
int temp = 0; //定义了全局变量,在线程中对其操作。
int main(void)
{
pthread_t pthread_1, pthread_2;
int ret = 0;
ret |= pthread_create(&pthread_1, NULL, pthread1_function, NULL);
if(0 != ret)
{
perror("pthread create.");
exit(1);
}
ret |= pthread_create(&pthread_2, NULL, pthread2_function, NULL);
if(0 != ret)
{
perror("pthread create.");
exit(1);
}
pthread_join(pthread_1, NULL);
pthread_join(pthread_2, NULL);
return 0;
}
void * pthread1_function(void *arg)
{
printf("Pthread1 start running.\n");
while(1)
{
printf("In pthread1_function, temp = %d.\n", temp++);
sleep(1);
}
return NULL;
}
void * pthread2_function(void *arg)
{
printf("Pthread2 start running.\n");
while(1)
{
printf("In pthread2_function, temp = %d.\n", temp++);
sleep(1);
}
return NULL;
}
运行结果:
运行结果可见,对这两个线程来说,temp是同一个变量,第一次,在线程1中为0,在线程2中+1为1;第二次在线程1中+1为2,在线程2中+1为3,依次下去。这是因为对于线程来说,资源是共享的,这一点与进程中的父子进程是有区别的。线程之间资源是共享的,所以实现线程之间的通讯比进程之间通讯要简单。
疑问?如果说多线程是并发执行的,但是temp变量是依次打印的,是不是可以说明线程之间执行有先后顺序呢?
5.3 总结
本次了解了多线程的创建方式,本质还是通过多次调用线程创建函数实现的。线程之间资源贡献,所以对于一个全局变量在多线程之间是可见的,通过这个特点,多线程也更好实现线程之间的通讯。