簡體   English   中英

Pthreads問題和一些問題

[英]Pthreads problem and a few questions

#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define NUM_THREADS 8

char *messages[NUM_THREADS];

struct thread_data
{
   int thread_id;
   int  sum;
   char *message;
};

struct thread_data thread_data_array[NUM_THREADS];

void *PrintHello(void *threadarg)
{
   int taskid, sum;
   char *hello_msg;
   struct thread_data *my_data;

   sleep(1);
   my_data = (struct thread_data *) threadarg;
   taskid = my_data->thread_id;
   sum = my_data->sum;
   hello_msg = my_data->message;
   printf("Thread %d: %s  Sum=%d\n", taskid, hello_msg, sum);
   pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
//int *taskids[NUM_THREADS];
int rc, t, sum;

sum=0;
messages[0] = "English: Hello World!";
messages[1] = "French: Bonjour, le monde!";
messages[2] = "Spanish: Hola al mundo";
messages[3] = "Klingon: Nuq neH!";
messages[4] = "German: Guten Tag, Welt!"; 
messages[5] = "Russian: Zdravstvytye, mir!";
messages[6] = "Japan: Sekai e konnichiwa!";
messages[7] = "Latin: Orbis, te saluto!";

for(t=0;t<NUM_THREADS;t++) {
  sum = sum + t;
  thread_data_array[t].thread_id = t;
  thread_data_array[t].sum = sum;
  thread_data_array[t].message = messages[t];
  printf("Creating thread %d\n", t);
  rc = pthread_create(&threads[t], NULL, PrintHello, (void *)&thread_data_array[t]);
  if (rc) {
    printf("ERROR; return code from pthread_create() is %d\n", rc);
    exit(-1);
    }
  }
pthread_exit(NULL);
}

上面的代碼給了我使用gcc在linux中的分段錯誤

作為初學者,我對線程有一些疑問

  1. 如果同時創建3個線程,並且必須退出,那么最后創建的線程會退出嗎?
  2. 每次創建和終止線程時,o / p可以不同嗎?如果可以,為什么?(我注意到他們這樣做了”);

如果同時創建3個線程,並且必須退出,那么最后創建的線程將退出?

答:無法保證第一個線程應首先退出。 創建它們后,操作系統會將它們視為單獨的實體,由操作系統決定哪個將首先退出。

每次創建和終止線程時,o / p是否可以不同?如果是,為什么? (我注意到他們這樣做了);

答:是的,它們確實有所不同,原因與上述相同。

每個線程的調度方式和時間完全取決於操作系統。 如果不深入研究OS代碼,就無法理解這一點。

在大多數pthread實現中(我並沒有全部使用,但是我已經使用了所有)。
當主線程退出時,所有其他線程停止執行,並且應用程序退出。

因此,在退出主線程之前,應等待(或殺死)所有子線程,然后再退出。
為此,我們有pthread_join()。

for(t=0;t<NUM_THREADS;t++)
{
    void* result;
    pthread_join(threads[t],&result);
}
// Now all the children are dead.

請注意,底層io系統不是線程安全的。
因此,如果有多個線程寫入IO,則可能會產生一些交錯。

您的代碼運行完美(我也在使用gcc)。

輸出:

Creating thread 0
Creating thread 1
Creating thread 2
Creating thread 3
Creating thread 4
Creating thread 5
Creating thread 6
Creating thread 7
Thread 1: French: Bonjour, le monde!  Sum=1
Thread 0: English: Hello World!  Sum=0
Thread 2: Spanish: Hola al mundo  Sum=3
Thread 4: German: Guten Tag, Welt!  Sum=10
Thread 3: Klingon: Nuq neH!  Sum=6
Thread 5: Russian: Zdravstvytye, mir!  Sum=15
Thread 6: Japan: Sekai e konnichiwa!  Sum=21
Thread 7: Latin: Orbis, te saluto!  Sum=28

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM