gpt4 book ai didi

c - 线程同时运行

转载 作者:太空宇宙 更新时间:2023-11-04 08:43:15 25 4
gpt4 key购买 nike

所以我想要 3 个线程,它们都递增一个全局整数。我认为,当创建一个线程时,它与主线程中的一个分支类似,将继续与新创建的线程同时执行代码。但这并不是实际发生的情况,因为直到第一个线程完成后才会创建第二个和第三个线程。

void * say_it( void * )
{
int count = 0;

while(BUFFER < 24)
{

//LOCK
if (pthread_mutex_lock(&output_lock) != 0)
{
perror("Could not lock output: ");
exit(-1);
}

//print message
cout << "TID: " << pthread_self() << " PID: " << "WORK IN PROGRESS " << "Buffer: " << BUFFER << endl;
BUFFER++;

//UNLOCK
if (pthread_mutex_unlock(&output_lock) != 0)
{
perror("Could not unlock output: ");
exit(-1);
}
count++;
}

//print final message
cout << "TID: " << pthread_self() << " worked on the buffer " << count << " times" << endl;

}

int main(int argc, char *argv[])
{

int num_threads = 3;
pthread_t *thread_ids;
void *p_status;

//Use unbuffered output on stdout
setvbuf(stdout, (char *) NULL, _IONBF, 0);

//Set up an output lock so that threads wait their turn to speak.
if (pthread_mutex_init(&output_lock, NULL)!=0)
{
perror("Could not create mutex for output: ");
return 1;
}

//Create 3 THREADS
thread_ids = new pthread_t[num_threads];

// generate threads
for (int i = 0; i < num_threads; i++)
{

int *arg = new int;
*arg = i;
if( pthread_create(&thread_ids[i],NULL,say_it,NULL) > 0)
{
perror("creating thread:");
return 2;
}

if (pthread_join(thread_ids[i], &p_status) != 0)
{
perror("trouble joining thread: ");
return 3;
}
}




return 0;
}

我也曾尝试在程序的某些区域放置 sleep(1),但没有成功。

谁能给我解释一下?谢谢!

最佳答案

当您调用 pthread_join 时,main 将阻塞直到该线程完成。在对线程调用 pthread_join 之前,您需要创建所有线程。

旁注:您在注释//join threads and print their return values 之后再次调用pthread_create。所有这些都需要删除。

关于c - 线程同时运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22703480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com