Macos pthread无法加入,出现未知错误
我计划使用pthreads和mach信号量来尝试将并行计算基本上分配给有限数量的cpu,而我无法让测试程序正常工作。现在,我有一些东西,只是通过线程和打印出一些标识符,以便我可以验证它的工作。代码非常简单,除了我在OSX上,所以我必须使用mach信号量而不是POSIX。我的代码在下面Macos pthread无法加入,出现未知错误,macos,pthreads,semaphore,Macos,Pthreads,Semaphore,我计划使用pthreads和mach信号量来尝试将并行计算基本上分配给有限数量的cpu,而我无法让测试程序正常工作。现在,我有一些东西,只是通过线程和打印出一些标识符,以便我可以验证它的工作。代码非常简单,除了我在OSX上,所以我必须使用mach信号量而不是POSIX。我的代码在下面 #include <iostream> #include <pthread.h> #include <semaphore.h> #include <errno.h>
#include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#include <mach/semaphore.h>
#include <mach/mach.h>
#define MAX_THREADS 256
semaphore_t free_CPU = 0;
void* t_function(void *arg) {
int* cur_number;
cur_number = (int*) arg;
kern_return_t test = semaphore_wait(free_CPU);
std::cout << "I am thread # " << *cur_number << ". Kernel return is " << test << std::endl;
semaphore_signal(free_CPU);
std::cout << "I am thread # " << *cur_number << ". I just signaled the semaphore." << std::endl;
pthread_exit(NULL);
}
int main (int argc, char * const argv[]) {
int num_reps = 10;
int n_threads = 1;
if (n_threads < MAX_THREADS) {
n_threads += 0;
} else {
n_threads = MAX_THREADS;
}
pthread_t threads[n_threads];
semaphore_create(mach_task_self(), &free_CPU, SYNC_POLICY_FIFO, 1);
// Loop over a bunch of things, feeding out to only nthreads threads at a time!
int i;
int* numbers = new int[num_reps];
for (i = 0; i < num_reps; i++) {
numbers[i] = i;
std::cout << "Throwing thread " << numbers[i] << std::endl;
int rc = pthread_create(&threads[i], NULL, &t_function, &numbers[i]);
if (rc) {
std::cout << "Failed to throw thread " << i << " Error: " << strerror(errno) << std::endl;
exit(1);
}
}
std::cout << "Threw all threads" << std::endl;
// Loop over threads to join
for (i = 0; i < num_reps; i++) {
std::cout << "Joining thread " << i << std::endl;
int rc = pthread_join(threads[i],NULL);
if (rc) {
std::cout << "Failed to join thread " << i << ". Error: " << strerror(errno) << std::endl;
exit(1);
}
}
semaphore_destroy(mach_task_self(), free_CPU);
delete[] numbers;
return 0;
}
对我来说,看起来一切都很好,只是当它试图连接线程8时,它只是咬了灰尘。我不知道发生了什么事。你的问题在于:
#define MAX_THREADS 256
:
int n_threads = 1;
if (n_threads < MAX_THREADS) {
n_threads += 0;
} else {
n_threads = MAX_THREADS;
}
pthread_t threads[n_threads];
#定义最大线程数256
:
int n_线程=1;
if(n螺纹<最大螺纹){
n_线程+=0;
}否则{
n_螺纹=最大_螺纹;
}
pthread_t线程[n_线程];
这将为您提供一个包含一个线程ID的数组。然后您将尝试填充其中的十个线程ID
我不完全确定你想用那件事干什么。在我看来,如果您只使用
num_reps
来对数组进行尺寸标注,它会工作得很好(您会得到一个包含十个元素的数组)。哦,上帝,非常感谢。我想会是这样的@用户1013641:不用叫我上帝,帕克斯会很好的:-)
#define MAX_THREADS 256
:
int n_threads = 1;
if (n_threads < MAX_THREADS) {
n_threads += 0;
} else {
n_threads = MAX_THREADS;
}
pthread_t threads[n_threads];