हे सभी लोग निम्नलिखित कोड पर विचार करते हुए (g++ -lpthread thread_test.cpp
के साथ संकलित) मुझे कैसे पता चलेगा कि मैं "thread_function" के अंदर से कौन सा नंबर थ्रेड हूं? और अगर आपके पास कोई अन्य सुझाव है तो मुझे बताएं।कक्षा में
धन्यवाद!
thread_test.cpp:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
class A {
public:
A();
void run();
private:
static void* thread_function(void *ptr);
pthread_t m_thread1, m_thread2;
static int m_global;
};
int A::m_global = 0;
A::A() {
int ret1 = pthread_create(&m_thread1, NULL, &A::thread_function, this);
int ret2 = pthread_create(&m_thread2, NULL, &A::thread_function, this);
}
void A::run() {
while (1) {
printf("parent incrementing...\n");
m_global++;
sleep(2);
}
}
void* A::thread_function(void *ptr) {
printf("I'm thread ?\n");
while (1) {
printf("thread global: %d\n", m_global);
sleep(1);
}
}
int main() {
A a;
a.run();
return 0;
}
ठीक है, मैं अब देखता हूं ... क्या मुझे कुछ प्रकार के थ्रेड विशिष्ट डेटा को स्टोर करने के लिए pthread_key_create जैसे कुछ का उपयोग करना चाहिए ताकि यह पहचान सके कि यह धागा 1 या 2 है या नहीं? मैं यह पता लगाने की कोशिश कर रहा हूं कि क्या pthread_key_create वास्तव में मैं चाहता हूं ... –
आप थ्रेड विशिष्ट चर का उपयोग कर सकते हैं लेकिन मुझे नहीं लगता कि यह आवश्यक है। जब भी आप वर्तमान थ्रेड नंबर का उपयोग करना चाहते हैं तो बस pthread_self() को कॉल करें। – danadam
आप एक संख्या के रूप में 'pthread_t' का उपयोग कैसे करते हैं? –