最近想開發thread的程式:

參考神人的程式:http://www.binarytides.com/server-client-example-c-sockets-linux/

自己實作如下:


++++++++++++++++++++
#include
#include

using namespace std;

static int a =9;

void *fnThreadFun(void *para){

int* i = (int* )para;

cout<<"i="<<*i<
cout<<"a="<
//...

///return ((void *)0);

}
void *print_message_function(void *ptr) {
        char *message;
        message = (char*) ptr;
        printf("%s\n", message);
        cout<<"a="<}


int main()
{
/*pthread_t thread1, thread2;
        char *message1 = "Thread 1";
        char *message2 = "Thread 2";
        int iret1, iret2;
        //Create independ threads each of which will execute function
        iret1 = pthread_create(&thread1, NULL, print_message_function, (void*) message1);
        iret2 = pthread_create(&thread2, NULL, print_message_function, (void*) message2);
        //Wait till threads are complete before main continues. Unless we wait and we run the risk of executing an exit/
        //which will terminate the process and all threads before the thread have completed.                           /
        pthread_join(thread1, NULL);
        pthread_join(thread2, NULL);
        printf("Thread1 returns: %d\n", iret1);
        printf("Thread2 returns: %d\n", iret2);
        return 0;
*/


    pthread_t ntid;

    //int a =1;

    for (int i=0;i<10;i++)
    {
         pthread_t ntid;
         pthread_create(&(ntid),NULL,fnThreadFun,(void*)&i);

        sleep(1);
    }
    //pthread_join(ntid, NULL);


    return 0;
}
++++++++++++++++++++++++
編譯選項:
g++ -g -pthread -o main main.cpp

執行結果:

[root@mos01_linux pThread]# ./main
i=0
a=9
i=1
a=9
i=2
a=9
i=3
a=9
i=4
a=9
i=5
a=9
i=6
a=9
i=7
a=9
i=8
a=9
++++++++++++++++++++++++++++++++


arrow
arrow
    全站熱搜

    rangerll 發表在 痞客邦 留言(0) 人氣()