Linux 线程的创建与结束

#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;


char message[]  = "init message !";


void* thread_function(void *);


int main()
{
    int res;
    pthread_t tid;
    void* thread_result;
    res = pthread_create(&tid, NULL, thread_function, (void *)message);


    if (res!=0)
    {
        std::cout << "create fail";
        exit(1);
    }
    res = pthread_join(tid, &thread_result);
    if (res!=0)
    {
        std::cout << "join fail";
        exit(1);
    }


    printf("Thread returned %s\n", (char*)thread_result);
    printf("Message is now %s\n", message); 
    return 0;
}
void* thread_function(void *arg)
{
    printf("thread is running argument is : %s\n", (char *)arg);
    sleep(1);
    strcpy(message, "see you!");
    pthread_exit((char *)"join get message");

}




#g++ thr.cpp -lpthread -o thr -ggdb && ./thr
thread is running argument is : init message !
Thread returned join get message
Message is now see you!


同步线程执行: 

#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;


int flag    = 1;
void *thread_function(void *);
int main()
{
    int res, count;
    pthread_t ThreadID;
    void* ThreadResult;


    res = pthread_create(&ThreadID, NULL, thread_function, NULL);
    if (res != 0)
    {
        perror("Thread Create Failed!");
        exit(EXIT_FAILURE);
    }


    while(count++ <=20)
    {
        if (flag == 1)
        {
            printf("1");
            flag    = 2;
        }
        else
        {
            sleep(1);
        }
    }


    printf("\nWait for thread to finish......\n");
    res = pthread_join(ThreadID, &ThreadResult);


    if (res != 0)
    {
        perror("Thread Join Failed");
        exit(EXIT_FAILURE);
    }
    return(EXIT_SUCCESS);
}


g++ thr.cpp -lpthread -o thr -ggdb && ./thr

121212121212121212121
Wait for thread to finish......





发布了145 篇原创文章 · 获赞 17 · 访问量 23万+

猜你喜欢

转载自blog.csdn.net/guichenglin/article/details/8227328