风声笔记

微信订阅号:fensnote 技术点滴,积少成多,水滴石穿,水到渠成……

导航

LInux下Posix的传统线程示例

简介

Linux线程是需要连接pthreat库,线程的使用比进程更灵活,需要注意的是线程间的互斥,或者说是资源共享问题。
C++11之后,C++标准库也引入了线程,并且使用非常方便,以后再介绍,这里先发一个简单的线程示例代码。

代码

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>


char message[32]={"Hello world!"};
void *thread_function(void *arg);


void *thread_function(void *arg)
{
    printf("thread_fonction is runing , argument is %s\n", (char *)arg);
    strcpy(message, "marked by thread");

    printf("thread_function finished\n");
    pthread_exit("Thank you for the cpu time\n");	
}


int
main(int argc, char **argv)
{   
    pthread_t a_thread;
    void *thread_result;

    if(pthread_create(&a_thread, NULL, thread_function, (void*)message ) < 0)
	{
		perror("pthread_create error:");
		exit(-1);
	}
	
    printf("writing for the thread to finish\n");
    if(pthread_join(a_thread, &thread_result) < 0)
    {
        perror("pthread_join error:");
        exit(0);
    }

    printf("in main, thread is exist, marked msg: %s \n", message);

    exit(0);
}

编译

编译的时候,需要加上pthread线程库

gcc pthreat.c -o test -lpthread

运行

程序启动后,主程序中,创建线程,然后等待线程退出,在线程函数里,会把message字符串修改掉。

./test 
in main, writing for the thread to finish
in thread, thread_fonction is runing , argument is Hello world!
in thread, thread_function finished
in main, thread is exist, marked msg: marked by thread 

posted on 2020-04-17 09:13  风声笔记  阅读(236)  评论(0编辑  收藏  举报