进程是维护应用程序所需的各种资源,并不执行什么。而线程才是真正的执行实体。为了让进程完成一定的工作,进程必须至少包含一个线程。
进程,直观点说,保存在硬盘上的程序运行以后,会在内存空间里形成一个独立的内存体,这个内存体有自己的地址空间,有自己的堆,上级挂靠单位是操作系统。操作系统会以进程为单位,分配系统资源,所以我们也说,进程是资源分配的最小单位。线程存在与进程当中,是操作系统调度执行的最小单位。
对于线程,新创建的线程和旧的线程的资源是共享的。
#include <pthread.h>
/* 创建线程 */
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
/* 参数:
thread: 线程ID
attr: 建议默认为NULL
start_routine: 回调函数名
arg: 传递给回调函数的参数
*/
/* 回调函数的格式:
static void* thread_start(void *arg);
*/
/* 返回值:
成功:0
失败:error number
*/
#include <pthread.h>
/* 等待线程结束,回收线程资源 */
int pthread_join(pthread_t thread, void **retval);
/* 参数:
thread: 线程ID
retval: 建议NULL
*/
/* 返回值:
成功:0
失败:error number
*/
代码
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
int data = 99;
/* 创建的第一个线程的回调函数 */
static void* start_pthread1(void* arg)
{
printf("%s\n",(char*)arg);
/* 改变数据 */
data = 100;
printf("data = %d\n",data);
return NULL;
}
/* 创建的第二个线程的回调函数 */
static void* start_pthread2(void* arg)
{
sleep(2);
printf("%s\n",(char*)arg);
printf("data = %d\n",data);
return NULL;
}
int main()
{
pthread_t thread1;
pthread_t thread2;
printf("data = %d\n",data);
/* 创建线程 */
pthread_create(&thread1,NULL,start_pthread1,(void*)("number one"));
pthread_create(&thread2,NULL,start_pthread2,(void*)("number two"));
/* 等待线程结束,回收资源 */
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
执行结果可见,在新线程1中改变的data,在新线程2中也改变了,说明线程的资源是共享的。
lingyun@manjaro ~/Document/CppCode/study gcc study.cpp -o study -lpthread
lingyun@manjaro ~/Document/CppCode/study ./study
data = 99
number one
data = 100
number two
data = 100