address JNI_FastGetField::generate_fast_get_int_field0(BasicType type) { const char *name = NULL; switch (type) { case T_BOOLEAN: name = "jni_fast_GetBooleanField"; break; case T_BYTE: name = "jni_fast_GetByteField"; break; case T_CHAR: name = "jni_fast_GetCharField"; break; case T_SHORT: name = "jni_fast_GetShortField"; break; case T_INT: name = "jni_fast_GetIntField"; break; case T_LONG: name = "jni_fast_GetLongField"; break; default: ShouldNotReachHere(); } ResourceMark rm; BufferBlob* blob = BufferBlob::create(name, BUFFER_SIZE); CodeBuffer cbuf(blob); MacroAssembler* masm = new MacroAssembler(&cbuf); address fast_entry = __ pc(); Label slow; ExternalAddress counter(SafepointSynchronize::safepoint_counter_addr()); __ mov32 (rcounter, counter); __ mov (robj, c_rarg1); __ testb (rcounter, 1); __ jcc (Assembler::notZero, slow); if (os::is_MP()) { __ xorptr(robj, rcounter); __ xorptr(robj, rcounter); // obj, since // robj ^ rcounter ^ rcounter == robj // robj is data dependent on rcounter. } __ clear_jweak_tag(robj); __ movptr(robj, Address(robj, 0)); // *obj __ mov (roffset, c_rarg2); __ shrptr(roffset, 2); // offset assert(count < LIST_CAPACITY, "LIST_CAPACITY too small"); speculative_load_pclist[count] = __ pc(); switch (type) { case T_BOOLEAN: __ movzbl (rax, Address(robj, roffset, Address::times_1)); break; case T_BYTE: __ movsbl (rax, Address(robj, roffset, Address::times_1)); break; case T_CHAR: __ movzwl (rax, Address(robj, roffset, Address::times_1)); break; case T_SHORT: __ movswl (rax, Address(robj, roffset, Address::times_1)); break; case T_INT: __ movl (rax, Address(robj, roffset, Address::times_1)); break; case T_LONG: __ movq (rax, Address(robj, roffset, Address::times_1)); break; default: ShouldNotReachHere(); } if (os::is_MP()) { __ lea(rcounter_addr, counter); // ca is data dependent on rax. __ xorptr(rcounter_addr, rax); __ xorptr(rcounter_addr, rax); __ cmpl (rcounter, Address(rcounter_addr, 0)); } else { __ cmp32 (rcounter, counter); } __ jcc (Assembler::notEqual, slow); __ ret (0); slowcase_entry_pclist[count++] = __ pc(); __ bind (slow); address slow_case_addr = NULL; switch (type) { case T_BOOLEAN: slow_case_addr = jni_GetBooleanField_addr(); break; case T_BYTE: slow_case_addr = jni_GetByteField_addr(); break; case T_CHAR: slow_case_addr = jni_GetCharField_addr(); break; case T_SHORT: slow_case_addr = jni_GetShortField_addr(); break; case T_INT: slow_case_addr = jni_GetIntField_addr(); break; case T_LONG: slow_case_addr = jni_GetLongField_addr(); } // tail call __ jump (ExternalAddress(slow_case_addr)); __ flush (); return fast_entry; }
int main(int argc, char *argv[]) { int i; //catch SIGINT and call handler signal(SIGINT, handleSigInt); //input //check if more then 3 arguments (min) if(argc < 3) { return getUsage(); } char *endptr = NULL; //get value to count to long int countTo = strtol(argv[1], &endptr, 10); //check if input is valid and greater than 0 if(*endptr || countTo <= 0) { return getUsage(); } long int proccount = strtol(argv[2], &endptr, 10); //check if nicevaluecount input is valid if(*endptr || argc != (proccount + 3) || proccount <= 0) { return getUsage(); } //array for the nice vals long int nicevals[proccount]; for(i = 3; i < proccount + 3; i++) { nicevals[i-3] = strtol(argv[i], &endptr, 10); //check if nice value between 0 and 19 (max range for non-root users) if(nicevals[i-3] < 0 || nicevals[i-3] > 19) { return getNiceUsage(); } else if(*endptr) { return getUsage(); } } //initalize pointer for processess id_t *ids = malloc(proccount * sizeof(id_t)); for(i = 0; i < proccount; i++) { ids[i] = 0; } pid_t pid; //fork proccount times for(i = 0; i < proccount; i++) { pid = fork(); if(pid == 0) { int which = PRIO_PROCESS; ids[i] = getpid(); //set nice value setpriority(which, ids[i], (int)nicevals[i]); int c = 1; double count = 0, sum = 0; while(gContinue) { count = counter(countTo); if(!breakup) { sum += count; printf("%d%s%f\n", i, " ", count); ++c; } } free(ids); exit(EXIT_SUCCESS); } else if(pid < 0) { perror("Something went wrong with the forking"); } } for(i = 0; i < proccount; i++) { int stat; //wait for all childs to end while (-1 == waitpid(ids[i], &stat, 0)); } free(ids); exit(EXIT_SUCCESS); }
TEST(MpiWordCounterTests, GetCountReturnsZeroByDefault) { mpi_word_counter counter("unused", std::vector<std::string>()); ASSERT_EQ(0, counter.get_count()); }
void PerfResourceCounterTest::testMove() { SizeCounter::Container container; SizeCounter counter(&container); qint64 origRequestSize = 0; qint64 origObtainSize = 0; counter.request(50, SizePayload(&origRequestSize)); counter.obtain(50, SizePayload(&origObtainSize)); QCOMPARE(origRequestSize, 50ll); QCOMPARE(origObtainSize, 0ll); QCOMPARE(counter.currentTotal(), 50ll); // Simple move qint64 moveRequestSize = 0; qint64 moveObtainSize = 0; counter.request(100, 50, SizePayload(&moveRequestSize)); counter.move(100, SizePayload(&moveObtainSize)); QCOMPARE(origRequestSize, 0ll); QCOMPARE(moveRequestSize, 100ll); QCOMPARE(moveObtainSize, 0ll); QCOMPARE(counter.currentTotal(), 100ll); // Move, reusing the same ID qint64 reuseRequestSize = 0; qint64 reuseObtainSize = 0; counter.request(200, 100, SizePayload(&reuseRequestSize)); counter.move(100, SizePayload(&reuseObtainSize)); QCOMPARE(moveRequestSize, 0ll); QCOMPARE(reuseRequestSize, 200ll); QCOMPARE(reuseObtainSize, 0ll); QCOMPARE(counter.currentTotal(), 200ll); // Move, implemented with request/obtain/release qint64 outerRequestSize = 0; counter.request(500, 100, &outerRequestSize); qint64 innerRequestSize = 0; counter.request(500, 50, &innerRequestSize); qint64 innerObtainSize = 0; counter.obtain(1000, &innerObtainSize); QCOMPARE(innerObtainSize, 0ll); QCOMPARE(innerRequestSize, 500ll); QCOMPARE(counter.currentTotal(), 700ll); qint64 innerReleaseSize = 0; counter.release(100, &innerReleaseSize); QCOMPARE(innerReleaseSize, 0ll); QCOMPARE(reuseRequestSize, 0ll); QCOMPARE(counter.currentTotal(), 500ll); qint64 outerMoveSize = 0; counter.move(1000, &outerMoveSize); QCOMPARE(outerMoveSize, 0ll); QCOMPARE(innerRequestSize, 0ll); QCOMPARE(outerRequestSize, 500ll); QCOMPARE(counter.currentTotal(), 500ll); // Failed simple move qint64 failedRequestSize = 0; counter.request(1000, 2000, &failedRequestSize); qint64 failedMoveSize = 0; counter.move(0, &failedMoveSize); QCOMPARE(failedRequestSize, 0ll); QCOMPARE(failedMoveSize, 0ll); QCOMPARE(outerRequestSize, 500ll); QCOMPARE(counter.currentTotal(), 500ll); // Failed move, using request/obtain/(not) release qint64 failedOuterRequestSize = 0; counter.request(1000, 2000, &failedOuterRequestSize); qint64 failedInnerRequestSize = 0; counter.request(2000, &failedInnerRequestSize); qint64 failedInnerObtainSize = 0; counter.obtain(0, &failedInnerObtainSize); QCOMPARE(failedInnerObtainSize, 0ll); QCOMPARE(failedInnerRequestSize, 0ll); QCOMPARE(outerRequestSize, 500ll); QCOMPARE(counter.currentTotal(), 500ll); qint64 failedOuterMoveSize = 0; counter.move(0, &failedOuterMoveSize); QCOMPARE(failedOuterRequestSize, 0ll); QCOMPARE(failedOuterMoveSize, 0ll); QCOMPARE(outerRequestSize, 500ll); QCOMPARE(counter.currentTotal(), 500ll); }
int main() { //treeNode *root = NULL; int x; int ch, num, num1; treeNode * temp; treeNode *med; int m = 1; do { printf("\nSelect a choice from the menu below."); printf("\n1. Generate Binary Search Tree"); printf("\n2. Print the BST in pre-order format"); printf("\n3. Print the BST in in-order format"); printf("\n4. Print the BST in post-order format"); printf("\n5. Print the BST in breadth-first format"); printf("\n6. Find a value in the BST"); printf("\n7. Find the minimum value in the BST nodes"); printf("\n8. Find the maximum value in the BST nodes"); printf("\n9. Calculate the average value of the BST nodes"); printf("\n10. Find the median value of the BST nodes"); printf("\n11. Calculate the sum of the BST nodes"); printf("\n12. Count the number of BST nodes"); printf("\n13. Delete a value in the BST"); printf("\n14. Exit Program"); printf("\n"); printf("\nEnter Choice: "); scanf("%d", &ch); switch (ch) { case 1: genrateTree(); printf("\n"); printf("\nTree in IN-ORDER : "); PrintInorder(root); printf("\n"); break; case 2: PrintPreorder(root); break; case 3: PrintInorder(root); break; case 4: PrintPostorder(root); break; case 5: printLevelOrder(root); break; case 6: printf("\nEnter the element to be Find in TREE: "); scanf("%d", &num); temp=Find(root, num); if (temp->data == num) { printf("Element Found\n"); } else { printf("Element NOT Found\n"); } break; case 7: temp = FindMin(root); printf("Minimum element is %d\n", temp->data); break; case 8: temp = FindMax(root); printf("Maximum element is %d\n", temp->data); break; case 9: in_order_sum(root); printf("Average element is %d\n", sum / counter(root)); sum = 0; break; case 10: med = medianTraverse(root, findHeight(root)); printf("Median Value is %d\n", med->data); break; case 11: in_order_sum(root); printf("\nThe sum of all the elements are:%d\n", sum); sum = 0; break; case 12: printf("Total Number of Nodes %d\n", counter(root)); break; case 13: PrintInorder(root); printf("\n"); printf("\nEnter the element to be Deleted: "); scanf("%d", &num); Delete(root, num); break; case 14: exit(0); break; default: exit(0); } //printf("%d", rootNode->data); printf("\n"); printf("\nIf you want to return to the menu, press 1."); printf("\nChoice: "); scanf("%d", &num); } while (num == 1); }
bool KNN::train_(LabelledClassificationData &trainingData,UINT K){ //Clear any previous models clear(); if( trainingData.getNumSamples() == 0 ){ errorLog << "train(LabelledClassificationData &trainingData) - Training data has zero samples!" << endl; return false; } //Set the dimensionality of the input data this->K = K; this->numFeatures = trainingData.getNumDimensions(); this->numClasses = trainingData.getNumClasses(); //TODO: In the future need to build a kdtree from the training data to allow better realtime prediction this->trainingData = trainingData; if( useScaling ){ ranges = this->trainingData.getRanges(); this->trainingData.scale(ranges, 0, 1); } //Set the class labels classLabels.resize(numClasses); for(UINT k=0; k<numClasses; k++){ classLabels[k] = trainingData.getClassTracker()[k].classLabel; } //Flag that the algorithm has been trained so we can compute the rejection thresholds trained = true; //If null rejection is enabled then compute the null rejection thresholds if( useNullRejection ){ //Set the null rejection to false so we can compute the values for it (this will be set back to its current value later) bool tempUseNullRejection = useNullRejection; useNullRejection = false; rejectionThresholds.clear(); //Compute the rejection thresholds for each of the K classes vector< double > counter(numClasses,0); trainingMu.resize( numClasses, 0 ); trainingSigma.resize( numClasses, 0 ); rejectionThresholds.resize( numClasses, 0 ); //Compute Mu for each of the classes const unsigned int numTrainingExamples = trainingData.getNumSamples(); vector< IndexedDouble > predictionResults( numTrainingExamples ); for(UINT i=0; i<numTrainingExamples; i++){ predict( trainingData[i].getSample(), K); UINT classLabelIndex = 0; for(UINT k=0; k<numClasses; k++){ if( predictedClassLabel == classLabels[k] ){ classLabelIndex = k; break; } } predictionResults[ i ].index = classLabelIndex; predictionResults[ i ].value = classDistances[ classLabelIndex ]; trainingMu[ classLabelIndex ] += predictionResults[ i ].value; counter[ classLabelIndex ]++; } for(UINT j=0; j<numClasses; j++){ trainingMu[j] /= counter[j]; } //Compute Sigma for each of the classes for(UINT i=0; i<numTrainingExamples; i++){ trainingSigma[predictionResults[i].index] += SQR(predictionResults[i].value - trainingMu[predictionResults[i].index]); } for(UINT j=0; j<numClasses; j++){ double count = counter[j]; if( count > 1 ){ trainingSigma[ j ] = sqrt( trainingSigma[j] / (count-1) ); }else{ trainingSigma[ j ] = 1.0; } } //Check to see if any of the mu or sigma values are zero or NaN bool errorFound = false; for(UINT j=0; j<numClasses; j++){ if( trainingMu[j] == 0 ){ warningLog << "TrainingMu[ " << j << " ] is zero for a K value of " << K << endl; } if( trainingSigma[j] == 0 ){ warningLog << "TrainingSigma[ " << j << " ] is zero for a K value of " << K << endl; } if( isnan( trainingMu[j] ) ){ errorLog << "TrainingMu[ " << j << " ] is NAN for a K value of " << K << endl; errorFound = true; } if( isnan( trainingSigma[j] ) ){ errorLog << "TrainingSigma[ " << j << " ] is NAN for a K value of " << K << endl; errorFound = true; } } if( errorFound ){ trained = false; return false; } //Recompute the rejection thresholds recomputeNullRejectionThresholds(); //Restore the actual state of the null rejection useNullRejection = tempUseNullRejection; }else{ //Resize the rejection thresholds but set the values to 0 rejectionThresholds.clear(); rejectionThresholds.resize( numClasses, 0 ); } return true; }
bool KNN::train_(const ClassificationData &trainingData,const UINT K){ //Set the dimensionality of the input data this->K = K; //Flag that the algorithm has been trained so we can compute the rejection thresholds trained = true; //If null rejection is enabled then compute the null rejection thresholds if( useNullRejection ){ //Set the null rejection to false so we can compute the values for it (this will be set back to its current value later) useNullRejection = false; nullRejectionThresholds.clear(); //Compute the rejection thresholds for each of the K classes VectorDouble counter(numClasses,0); trainingMu.resize( numClasses, 0 ); trainingSigma.resize( numClasses, 0 ); nullRejectionThresholds.resize( numClasses, 0 ); //Compute Mu for each of the classes const unsigned int numTrainingExamples = trainingData.getNumSamples(); vector< IndexedDouble > predictionResults( numTrainingExamples ); for(UINT i=0; i<numTrainingExamples; i++){ predict( trainingData[i].getSample(), K); UINT classLabelIndex = 0; for(UINT k=0; k<numClasses; k++){ if( predictedClassLabel == classLabels[k] ){ classLabelIndex = k; break; } } predictionResults[ i ].index = classLabelIndex; predictionResults[ i ].value = classDistances[ classLabelIndex ]; trainingMu[ classLabelIndex ] += predictionResults[ i ].value; counter[ classLabelIndex ]++; } for(UINT j=0; j<numClasses; j++){ trainingMu[j] /= counter[j]; } //Compute Sigma for each of the classes for(UINT i=0; i<numTrainingExamples; i++){ trainingSigma[predictionResults[i].index] += SQR(predictionResults[i].value - trainingMu[predictionResults[i].index]); } for(UINT j=0; j<numClasses; j++){ double count = counter[j]; if( count > 1 ){ trainingSigma[ j ] = sqrt( trainingSigma[j] / (count-1) ); }else{ trainingSigma[ j ] = 1.0; } } //Check to see if any of the mu or sigma values are zero or NaN bool errorFound = false; for(UINT j=0; j<numClasses; j++){ if( trainingMu[j] == 0 ){ warningLog << "TrainingMu[ " << j << " ] is zero for a K value of " << K << endl; } if( trainingSigma[j] == 0 ){ warningLog << "TrainingSigma[ " << j << " ] is zero for a K value of " << K << endl; } if( std::isnan( trainingMu[j] ) ){ errorLog << "TrainingMu[ " << j << " ] is NAN for a K value of " << K << endl; errorFound = true; } if( std::isnan( trainingSigma[j] ) ){ errorLog << "TrainingSigma[ " << j << " ] is NAN for a K value of " << K << endl; errorFound = true; } } if( errorFound ){ trained = false; return false; } //Compute the rejection thresholds for(unsigned int j=0; j<numClasses; j++){ nullRejectionThresholds[j] = trainingMu[j] + (trainingSigma[j]*nullRejectionCoeff); } //Restore the actual state of the null rejection useNullRejection = true; }else{ //Resize the rejection thresholds but set the values to 0 nullRejectionThresholds.clear(); nullRejectionThresholds.resize( numClasses, 0 ); } return true; }
address JNI_FastGetField::generate_fast_get_long_field() { const char *name = "jni_fast_GetLongField"; ResourceMark rm; BufferBlob* b = BufferBlob::create(name, BUFFER_SIZE*wordSize); address fast_entry = b->instructions_begin(); CodeBuffer cbuf(fast_entry, b->instructions_size()); MacroAssembler* masm = new MacroAssembler(&cbuf); Label slow; // stack layout: offset from rsp (in words): // old rsi 0 // return pc 1 // jni env 2 // obj 3 // jfieldID 4 ExternalAddress counter(SafepointSynchronize::safepoint_counter_addr()); __ push (rsi); __ mov32 (rcx, counter); __ testb (rcx, 1); __ jcc (Assembler::notZero, slow); if (os::is_MP()) { __ mov(rax, rcx); __ andptr(rax, 1); // rax, must end up 0 __ movptr(rdx, Address(rsp, rax, Address::times_1, 3*wordSize)); // obj, notice rax, is 0. // rdx is data dependent on rcx. } else { __ movptr(rdx, Address(rsp, 3*wordSize)); // obj } __ movptr(rsi, Address(rsp, 4*wordSize)); // jfieldID __ movptr(rdx, Address(rdx, 0)); // *obj __ shrptr(rsi, 2); // offset assert(count < LIST_CAPACITY-1, "LIST_CAPACITY too small"); speculative_load_pclist[count++] = __ pc(); __ movptr(rax, Address(rdx, rsi, Address::times_1)); #ifndef _LP64 speculative_load_pclist[count] = __ pc(); __ movl(rdx, Address(rdx, rsi, Address::times_1, 4)); #endif // _LP64 if (os::is_MP()) { __ lea(rsi, counter); __ xorptr(rsi, rdx); __ xorptr(rsi, rax); __ xorptr(rsi, rdx); __ xorptr(rsi, rax); __ cmp32(rcx, Address(rsi, 0)); // ca1 is the same as ca because // rax, ^ rdx ^ counter_addr ^ rax, ^ rdx = address // ca1 is data dependent on both rax, and rdx. } else { __ cmp32(rcx, counter); } __ jcc (Assembler::notEqual, slow); __ pop (rsi); #ifndef _WINDOWS __ ret (0); #else // __stdcall calling convention __ ret (3*wordSize); #endif slowcase_entry_pclist[count-1] = __ pc(); slowcase_entry_pclist[count++] = __ pc(); __ bind (slow); __ pop (rsi); address slow_case_addr = jni_GetLongField_addr();; // tail call __ jump (ExternalAddress(slow_case_addr)); __ flush (); #ifndef _WINDOWS return fast_entry; #else jni_fast_GetLongField_fp = (GetLongField_t)fast_entry; return os::win32::fast_jni_accessor_wrapper(T_LONG); #endif }
address JNI_FastGetField::generate_fast_get_float_field0(BasicType type) { const char *name; switch (type) { case T_FLOAT: name = "jni_fast_GetFloatField"; break; case T_DOUBLE: name = "jni_fast_GetDoubleField"; break; default: ShouldNotReachHere(); } ResourceMark rm; BufferBlob* b = BufferBlob::create(name, BUFFER_SIZE*wordSize); address fast_entry = b->instructions_begin(); CodeBuffer cbuf(fast_entry, b->instructions_size()); MacroAssembler* masm = new MacroAssembler(&cbuf); Label slow_with_pop, slow; // stack layout: offset from rsp (in words): // return pc 0 // jni env 1 // obj 2 // jfieldID 3 ExternalAddress counter(SafepointSynchronize::safepoint_counter_addr()); __ mov32 (rcx, counter); __ testb (rcx, 1); __ jcc (Assembler::notZero, slow); if (os::is_MP()) { __ mov(rax, rcx); __ andptr(rax, 1); // rax, must end up 0 __ movptr(rdx, Address(rsp, rax, Address::times_1, 2*wordSize)); // obj, notice rax, is 0. // rdx is data dependent on rcx. } else { __ movptr(rdx, Address(rsp, 2*wordSize)); // obj } __ movptr(rax, Address(rsp, 3*wordSize)); // jfieldID __ movptr(rdx, Address(rdx, 0)); // *obj __ shrptr(rax, 2); // offset assert(count < LIST_CAPACITY, "LIST_CAPACITY too small"); speculative_load_pclist[count] = __ pc(); switch (type) { #ifndef _LP64 case T_FLOAT: __ fld_s (Address(rdx, rax, Address::times_1)); break; case T_DOUBLE: __ fld_d (Address(rdx, rax, Address::times_1)); break; #else case T_FLOAT: __ movflt (xmm0, Address(robj, roffset, Address::times_1)); break; case T_DOUBLE: __ movdbl (xmm0, Address(robj, roffset, Address::times_1)); break; #endif // _LP64 default: ShouldNotReachHere(); } Address ca1; if (os::is_MP()) { __ fst_s (Address(rsp, -4)); __ lea(rdx, counter); __ movl (rax, Address(rsp, -4)); // garbage hi-order bits on 64bit are harmless. __ xorptr(rdx, rax); __ xorptr(rdx, rax); __ cmp32(rcx, Address(rdx, 0)); // rax, ^ counter_addr ^ rax, = address // ca1 is data dependent on the field // access. } else { __ cmp32(rcx, counter); } __ jcc (Assembler::notEqual, slow_with_pop); #ifndef _WINDOWS __ ret (0); #else // __stdcall calling convention __ ret (3*wordSize); #endif __ bind (slow_with_pop); // invalid load. pop FPU stack. __ fstp_d (0); slowcase_entry_pclist[count++] = __ pc(); __ bind (slow); address slow_case_addr; switch (type) { case T_FLOAT: slow_case_addr = jni_GetFloatField_addr(); break; case T_DOUBLE: slow_case_addr = jni_GetDoubleField_addr(); break; default: ShouldNotReachHere(); } // tail call __ jump (ExternalAddress(slow_case_addr)); __ flush (); #ifndef _WINDOWS return fast_entry; #else switch (type) { case T_FLOAT: jni_fast_GetFloatField_fp = (GetFloatField_t)fast_entry; break; case T_DOUBLE: jni_fast_GetDoubleField_fp = (GetDoubleField_t)fast_entry; } return os::win32::fast_jni_accessor_wrapper(type); #endif }
mach_msg_return_t ipc_mqueue_send( ipc_kmsg_t kmsg, mach_msg_option_t option, mach_msg_timeout_t time_out) { ipc_port_t port; port = (ipc_port_t) kmsg->ikm_header.msgh_remote_port; assert(IP_VALID(port)); ip_lock(port); if (port->ip_receiver == ipc_space_kernel) { ipc_kmsg_t reply; /* * We can check ip_receiver == ipc_space_kernel * before checking that the port is active because * ipc_port_dealloc_kernel clears ip_receiver * before destroying a kernel port. */ assert(ip_active(port)); ip_unlock(port); reply = ipc_kobject_server(kmsg); if (reply != IKM_NULL) ipc_mqueue_send_always(reply); return MACH_MSG_SUCCESS; } for (;;) { ipc_thread_t self; /* * Can't deliver to a dead port. * However, we can pretend it got sent * and was then immediately destroyed. */ if (!ip_active(port)) { /* * We can't let ipc_kmsg_destroy deallocate * the port right, because we might end up * in an infinite loop trying to deliver * a send-once notification. */ ip_release(port); ip_check_unlock(port); kmsg->ikm_header.msgh_remote_port = MACH_PORT_NULL; ipc_kmsg_destroy(kmsg); return MACH_MSG_SUCCESS; } /* * Don't block if: * 1) We're under the queue limit. * 2) Caller used the MACH_SEND_ALWAYS internal option. * 3) Message is sent to a send-once right. */ if ((port->ip_msgcount < port->ip_qlimit) || (option & MACH_SEND_ALWAYS) || (MACH_MSGH_BITS_REMOTE(kmsg->ikm_header.msgh_bits) == MACH_MSG_TYPE_PORT_SEND_ONCE)) break; /* must block waiting for queue to clear */ self = current_thread(); if (option & MACH_SEND_TIMEOUT) { if (time_out == 0) { ip_unlock(port); return MACH_SEND_TIMED_OUT; } thread_will_wait_with_timeout(self, time_out); } else thread_will_wait(self); ipc_thread_enqueue(&port->ip_blocked, self); self->ith_state = MACH_SEND_IN_PROGRESS; ip_unlock(port); counter(c_ipc_mqueue_send_block++); thread_block((void (*)(void)) 0); ip_lock(port); /* why did we wake up? */ if (self->ith_state == MACH_MSG_SUCCESS) continue; assert(self->ith_state == MACH_SEND_IN_PROGRESS); /* take ourselves off blocked queue */ ipc_thread_rmqueue(&port->ip_blocked, self); /* * Thread wakeup-reason field tells us why * the wait was interrupted. */ switch (self->ith_wait_result) { case THREAD_INTERRUPTED: /* send was interrupted - give up */ ip_unlock(port); return MACH_SEND_INTERRUPTED; case THREAD_TIMED_OUT: /* timeout expired */ assert(option & MACH_SEND_TIMEOUT); time_out = 0; break; case THREAD_RESTART: default: #if MACH_ASSERT assert(!"ipc_mqueue_send"); #else panic("ipc_mqueue_send"); #endif } } if (kmsg->ikm_header.msgh_bits & MACH_MSGH_BITS_CIRCULAR) { ip_unlock(port); /* don't allow the creation of a circular loop */ ipc_kmsg_destroy(kmsg); return MACH_MSG_SUCCESS; } { ipc_mqueue_t mqueue; ipc_pset_t pset; ipc_thread_t receiver; ipc_thread_queue_t receivers; port->ip_msgcount++; assert(port->ip_msgcount > 0); pset = port->ip_pset; if (pset == IPS_NULL) mqueue = &port->ip_messages; else mqueue = &pset->ips_messages; imq_lock(mqueue); receivers = &mqueue->imq_threads; /* * Can unlock the port now that the msg queue is locked * and we know the port is active. While the msg queue * is locked, we have control of the kmsg, so the ref in * it for the port is still good. If the msg queue is in * a set (dead or alive), then we're OK because the port * is still a member of the set and the set won't go away * until the port is taken out, which tries to lock the * set's msg queue to remove the port's msgs. */ ip_unlock(port); /* check for a receiver for the message */ for (;;) { receiver = ipc_thread_queue_first(receivers); if (receiver == ITH_NULL) { /* no receivers; queue kmsg */ ipc_kmsg_enqueue_macro(&mqueue->imq_messages, kmsg); imq_unlock(mqueue); break; } ipc_thread_rmqueue_first_macro(receivers, receiver); assert(ipc_kmsg_queue_empty(&mqueue->imq_messages)); if (kmsg->ikm_header.msgh_size <= receiver->ith_msize) { /* got a successful receiver */ receiver->ith_state = MACH_MSG_SUCCESS; receiver->ith_kmsg = kmsg; receiver->ith_seqno = port->ip_seqno++; imq_unlock(mqueue); thread_go(receiver); break; } receiver->ith_state = MACH_RCV_TOO_LARGE; receiver->ith_msize = kmsg->ikm_header.msgh_size; thread_go(receiver); } } current_task()->messages_sent++; return MACH_MSG_SUCCESS; }
mach_msg_return_t ipc_mqueue_receive( ipc_mqueue_t mqueue, mach_msg_option_t option, mach_msg_size_t max_size, mach_msg_timeout_t time_out, boolean_t resume, void (*continuation)(void), ipc_kmsg_t *kmsgp, mach_port_seqno_t *seqnop) { ipc_port_t port; ipc_kmsg_t kmsg; mach_port_seqno_t seqno; { ipc_kmsg_queue_t kmsgs = &mqueue->imq_messages; ipc_thread_t self = current_thread(); if (resume) goto after_thread_block; for (;;) { kmsg = ipc_kmsg_queue_first(kmsgs); if (kmsg != IKM_NULL) { /* check space requirements */ if (kmsg->ikm_header.msgh_size > max_size) { * (mach_msg_size_t *) kmsgp = kmsg->ikm_header.msgh_size; imq_unlock(mqueue); return MACH_RCV_TOO_LARGE; } ipc_kmsg_rmqueue_first_macro(kmsgs, kmsg); port = (ipc_port_t) kmsg->ikm_header.msgh_remote_port; seqno = port->ip_seqno++; break; } /* must block waiting for a message */ if (option & MACH_RCV_TIMEOUT) { if (time_out == 0) { imq_unlock(mqueue); return MACH_RCV_TIMED_OUT; } thread_will_wait_with_timeout(self, time_out); } else thread_will_wait(self); ipc_thread_enqueue_macro(&mqueue->imq_threads, self); self->ith_state = MACH_RCV_IN_PROGRESS; self->ith_msize = max_size; imq_unlock(mqueue); if (continuation != (void (*)(void)) 0) { counter(c_ipc_mqueue_receive_block_user++); } else { counter(c_ipc_mqueue_receive_block_kernel++); } thread_block(continuation); after_thread_block: imq_lock(mqueue); /* why did we wake up? */ if (self->ith_state == MACH_MSG_SUCCESS) { /* pick up the message that was handed to us */ kmsg = self->ith_kmsg; seqno = self->ith_seqno; port = (ipc_port_t) kmsg->ikm_header.msgh_remote_port; break; } switch (self->ith_state) { case MACH_RCV_TOO_LARGE: /* pick up size of the too-large message */ * (mach_msg_size_t *) kmsgp = self->ith_msize; /* fall-through */ case MACH_RCV_PORT_DIED: case MACH_RCV_PORT_CHANGED: /* something bad happened to the port/set */ imq_unlock(mqueue); return self->ith_state; case MACH_RCV_IN_PROGRESS: /* * Awakened for other than IPC completion. * Remove ourselves from the waiting queue, * then check the wakeup cause. */ ipc_thread_rmqueue(&mqueue->imq_threads, self); switch (self->ith_wait_result) { case THREAD_INTERRUPTED: /* receive was interrupted - give up */ imq_unlock(mqueue); return MACH_RCV_INTERRUPTED; case THREAD_TIMED_OUT: /* timeout expired */ assert(option & MACH_RCV_TIMEOUT); time_out = 0; break; case THREAD_RESTART: default: #if MACH_ASSERT assert(!"ipc_mqueue_receive"); #else panic("ipc_mqueue_receive"); #endif } break; default: #if MACH_ASSERT assert(!"ipc_mqueue_receive: strange ith_state"); #else panic("ipc_mqueue_receive: strange ith_state"); #endif } } /* we have a kmsg; unlock the msg queue */ imq_unlock(mqueue); assert(kmsg->ikm_header.msgh_size <= max_size); } { ipc_marequest_t marequest; marequest = kmsg->ikm_marequest; if (marequest != IMAR_NULL) { ipc_marequest_destroy(marequest); kmsg->ikm_marequest = IMAR_NULL; } assert((kmsg->ikm_header.msgh_bits & MACH_MSGH_BITS_CIRCULAR) == 0); assert(port == (ipc_port_t) kmsg->ikm_header.msgh_remote_port); ip_lock(port); if (ip_active(port)) { ipc_thread_queue_t senders; ipc_thread_t sender; assert(port->ip_msgcount > 0); port->ip_msgcount--; senders = &port->ip_blocked; sender = ipc_thread_queue_first(senders); if ((sender != ITH_NULL) && (port->ip_msgcount < port->ip_qlimit)) { ipc_thread_rmqueue(senders, sender); sender->ith_state = MACH_MSG_SUCCESS; thread_go(sender); } } ip_unlock(port); } current_task()->messages_received++; *kmsgp = kmsg; *seqnop = seqno; return MACH_MSG_SUCCESS; }
static int load() { FreeTypeDecoder::initialize(); ShowWindow(GetConsoleWindow(), SW_HIDE); Graphics3D * graphics = D3DGraphics::initialize(); FinalAction finally(D3DGraphics::free); graphics->setClearColor({0.0f, 0.0f, 0.0f}); Handle<Window> window(graphics, 0, 0, 1024, 758); Handle<WindowBackground> back(window); back->name = "Background"; Handle<Panel> frame(back); frame->setPlacement({0.5f, 0.5f, 0.5f, 0.5f}, {-300, -300, 300, 300}); frame << [](const DrawParams & p) { p.graphics->setColor({0.25f, 0.25f, 0.25f}); p.graphics->rectangle(p.clipped); }; Handle<Panel> frame0(frame); frame0->setPlacement(ModelMask::FullSize, {4, 4, -4, -4}); frame0 << [](const DrawParams & p) { p.graphics->setColor({0.5f, 0.5f, 0.5f}); p.graphics->rectangle(p.clipped); }; Handle<Panel> frame1(frame0); frame1->setPlacement(ModelMask::FullSize, {3, 3, -3, -3}); frame1 << [](const DrawParams & p) { p.graphics->setColor({0.75f, 0.75f, 0.75f}); p.graphics->rectangle(p.clipped); }; Handle<Panel> frame2(frame1); frame2->setPlacement(ModelMask::FullSize, {2, 2, -2, -2}); frame2 << [](const DrawParams & p) { p.graphics->setColor({1.0f, 1.0f, 1.0f}); p.graphics->rectangle(p.clipped); }; Handle<Panel> panel(frame2); panel->setPlacement(ModelMask::FullSize, {1, 1, -1, -1}); panel << [](const DrawParams & p) { p.graphics->setColor({0.0f, 0.0f, 0.0f}); p.graphics->rectangle(p.clipped); }; auto arial = Font::load("arial.ttf"); graphics->bind(arial); graphics->setFontSize(16); Handle<String> project_name("Independence"); Handle<Panel> project_name_panel(back); project_name_panel->setPlacement(10, 10, 0, 0); project_name_panel->setSize(graphics->getTextSize(*project_name)); project_name_panel << [arial, project_name](const DrawParams & p) { auto & graphics = p.graphics; auto & region = p.region; graphics->bind(arial); graphics->setFontSize(16); p.graphics->setColor({1.0f, 1.0f, 1.0f}); graphics->draw(region.left, region.top, *project_name); }; Handle<String> text("Press Esc to quit"); Handle<Panel> text_panel(back); text_panel->setPlacement(ModelMask::RightTop, {0, 10, -10, 0}); text_panel->setSize(graphics->getTextSize(*text)); text_panel << [arial, text](const DrawParams & p) { auto & graphics = p.graphics; auto & region = p.region; graphics->bind(arial); graphics->setFontSize(16); p.graphics->setColor({1.0f, 1.0f, 1.0f}); graphics->draw(region.left, region.top, *text); }; Handle<FpsCounter> counter(emptiness); Handle<Panel> fps_panel(back); fps_panel->setPlacement({0.5f, 1.0f, 0.5f, 1.0f}, {-40, -30, 40, -10}); fps_panel << [counter, arial](const DrawParams & p) { auto graphics = p.graphics; graphics->bind(arial); graphics->setFontSize(16); auto text = String(counter->get()) + " fps"; auto textSize = graphics->getTextSize(text); int left = p.region.left + (p.region.width() - textSize.x) / 2; int top = p.region.top + (p.region.height() - textSize.y) / 2; p.graphics->setColor({1.0f, 1.0f, 1.0f}); graphics->draw(left, top, text); }; Handle<Scene> scene(panel); scene->append<Snake>(color(1.0f, 0.0f, 0.0f)); scene->append<Snake>(color(1.0f, 0.5f, 0.0f)); scene->append<Snake>(color(1.0f, 1.0f, 0.0f)); scene->append<Snake>(color(0.0f, 1.0f, 0.0f)); scene->append<Snake>(color(0.0f, 1.0f, 1.0f)); scene->append<Snake>(color(0.0f, 0.0f, 1.0f)); scene->append<Snake>(color(0.5f, 0.0f, 1.0f)); connect(*window, onWindowKeyDown); window->setBorderStyle(BorderStyle::Static); window->setCaption("Independence"); window->centralize(); window->show(); ThreadLoop::add(processWindowMessage); ThreadLoop::add([scene, window, counter, fps_panel] () mutable { //std::this_thread::sleep_for(1ms); counter->next(); window->invalidate(fps_panel); scene->invalidate(); window->validate(); return 0; }); ThreadLoop::run(); return 0; }
void start_counter() { /* Get cycle counter */ cyc_hi = 0; cyc_lo = counter(); }
// One read is counted ONLY ONCE. If two regions overlap, reads mapped to both regions // will be counted to the region with samller start position bool GenomeRegionSeqStats::PartialUpdate_Unique(String &chr, int start, int end) { int ¤tIndex = genomeRegions_currentIndex[chr]; vector< std::pair<int, int> > ®ion = genomeRegions[chr]; String CSE = chr+":"+region[currentIndex].first+":"+region[currentIndex].second; vector<String> group = genomeRegionGroups[CSE]; vector<int> counter(group.size(), 0); // completely mapped to a region // ****** read // --------------- region if(start>=region[currentIndex].first && end<=region[currentIndex].second) { genomeRegionStats[CSE].nReads_complete++; genomeRegionStats[CSE].nReads_all++; genomeRegionStats[CSE].nBases += (end-start); if(group.size()>0) { for(unsigned int g=0; g<group.size();g++) { if((++counter[g])>1) continue; groupStats[group[g]].nReads_complete++; groupStats[group[g]].nReads_all++; groupStats[group[g]].nBases += (end-start); //positions are 0-based } } return(true); } // completely cover the entire region // ******************* read // --------- region if(start<=region[currentIndex].first && end>=region[currentIndex].second) { genomeRegionStats[CSE].nReads_all++; genomeRegionStats[CSE].nReads_complete++; genomeRegionStats[CSE].nBases += (region[currentIndex].second-region[currentIndex].first); // positions are 0-based if(group.size()>0) { for(unsigned int g=0; g<group.size(); g++) { if((++counter[g])>1) continue; groupStats[group[g]].nReads_complete++; groupStats[group[g]].nReads_all++; groupStats[group[g]].nBases += (region[currentIndex].second-region[currentIndex].first); //positions are 0-based } } return(true); } // partial mapping left // ************* read // -------------------------- region if(start<region[currentIndex].first && end>(region[currentIndex].first+minOverlapLen-1)) { genomeRegionStats[CSE].nReads_all++; genomeRegionStats[CSE].nBases += (end-region[currentIndex].first); if(group.size()>0) { for(unsigned int g=0; g<group.size(); g++) { if((++counter[g])>1) continue; groupStats[group[g]].nReads_all++; groupStats[group[g]].nBases += (end-region[currentIndex].first); //positions are 0-based } } return(true); } // partial mapping right // **************** read // ----------------------- region if(start<(region[currentIndex].second-minOverlapLen+1) && end>region[currentIndex].second) { genomeRegionStats[CSE].nReads_all++; genomeRegionStats[CSE].nBases += (region[currentIndex].second-start); // positions are 0-based if(group.size()>0) { for(unsigned int g=0; g<group.size(); g++){ if((++counter[g])>1) continue; groupStats[group[g]].nReads_all++; groupStats[group[g]].nBases += (region[currentIndex].second-start); //positions are 0-based } } return(true); } return(false); }
int main() { //window properties sf::RenderWindow pong(sf::VideoMode(RENDERWIDTH, RENDERHEIGHT, 32), "GameName", sf::Style::Fullscreen); pong.setMouseCursorVisible(false); pong.setFramerateLimit(60); //music sf::Music bgm; bgm.openFromFile("multimedia/audio/musica.wav"); bgm.setPitch(1); bgm.setLoop(true); bgm.play(); //sound sf::SoundBuffer buffer1; buffer1.loadFromFile("multimedia/audio/bounce.wav"); sf::Sound bounce; bounce.setBuffer(buffer1); sf::SoundBuffer buffer2; buffer2.loadFromFile("multimedia/audio/point.wav"); sf::Sound point; point.setBuffer(buffer2); //ncp properties sf::RectangleShape ncp(sf::Vector2f(5, RENDERHEIGHT / 1.6)); ncp.setFillColor(sf::Color(50, 50, 50)); ncp.setPosition(RENDERWIDTH / 2, RENDERHEIGHT / 2 - (RENDERHEIGHT / 1.6) / 2 ); //player 1 properties int p1Len = 100; sf::RectangleShape player1(sf::Vector2f(10, p1Len)); player1.setFillColor(sf::Color(0, 0, 255)); player1.setPosition(0, RENDERHEIGHT / 2 - player1.getSize().y / 2); int player1Score = 0; //player 2 properties int p2Len = 100; sf::RectangleShape player2(sf::Vector2f(10, p2Len)); player2.setFillColor(sf::Color(255, 0, 0)); player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT / 2 - player2.getSize().y / 2); int player2Score = 0; //ball properties sf::CircleShape ball(10, 25); ball.setFillColor(sf::Color(255, 255, 255)); ball.setPosition(RENDERWIDTH / 2 - ball.getRadius(), RENDERHEIGHT / 2 - ball.getRadius()); float BALLSPEED = 2; float ballVelX = -BALLSPEED, ballVelY = -BALLSPEED; float ballX = RENDERWIDTH / 2 - ball.getRadius(), ballY = RENDERHEIGHT / 2 - ball.getRadius(); float ballDiameter = ball.getRadius() * 2; //score-timer text sf::Font font; font.loadFromFile("fonts/LiberationSerif-Regular.ttf"); sf::Text score1("0", font, 80); score1.setPosition(RENDERWIDTH / 4, 0); sf::Text score2("0", font, 80); score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0); sf::Text timer1("", font, 80); timer1.setPosition(0 , 5 * RENDERHEIGHT / 6); sf::Text timer2("", font, 80); timer2.setPosition(RENDERWIDTH / 2 - timer2.getLocalBounds().width, 5 * RENDERHEIGHT / 6); int time1 = 0; int time2 = 0; //gameover sf::Text gameover("GAME OVER", font, 120); gameover.setColor(sf::Color::Red); gameover.setPosition(0, RENDERHEIGHT / 3); //game loop while(player1Score + player2Score != 3) { sf::Event event; while(pong.pollEvent(event)) { if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) pong.close(); } //score for player one winning if(player1Score == player2Score + 1) { timer1.setString(convertInt(time1 += 2)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 2) { timer1.setString(convertInt(time1 += 4)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 3) { timer1.setString(convertInt(time1 += 8)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 4) { timer1.setString(convertInt(time1 += 16)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 5) { timer1.setString(convertInt(time1 += 32)); timer2.setString(convertInt(time2 += 1)); } if(player1Score == player2Score + 6) { timer1.setString(convertInt(time1 += 64)); timer2.setString(convertInt(time2 += 1)); } //score on equals if(player1Score == player2Score) { timer1.setString(convertInt(time1 += 1)); timer2.setString(convertInt(time2 += 1)); } //score for player two winning if(player2Score == player1Score + 1) { timer2.setString(convertInt(time2 += 2)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 2) { timer2.setString(convertInt(time2 += 4)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 3) { timer2.setString(convertInt(time2 += 8)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 4) { timer2.setString(convertInt(time2 += 16)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 5) { timer2.setString(convertInt(time2 += 32)); timer1.setString(convertInt(time1 += 1)); } if(player2Score == player1Score + 6) { timer2.setString(convertInt(time2 += 64)); timer1.setString(convertInt(time1 += 1)); } //player 1 movement if(sf::Keyboard::isKeyPressed(sf::Keyboard::W)) player1.move(0, -10); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::S)) player1.move(0, 10); //player 2 movement if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) player2.move(0, -10); else if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) player2.move(0, 10); //player 1 and wall collision if(player1.getPosition().y <= 0) player1.setPosition(0, 0); if(player1.getPosition().y >= RENDERHEIGHT - player1.getSize().y) player1.setPosition(0, RENDERHEIGHT - player1.getSize().y); //player 2 and wall collision if(player2.getPosition().y <= 0) player2.setPosition(RENDERWIDTH - player2.getSize().x, 0); if(player2.getPosition().y >= RENDERHEIGHT - player2.getSize().y) player2.setPosition(RENDERWIDTH - player2.getSize().x, RENDERHEIGHT - player2.getSize().y); //ball and wall collision if(ball.getPosition().y <= 0 || ball.getPosition().y >= RENDERHEIGHT - ballDiameter) { ballVelY *= -1; bounce.play(); } //ball and player 1 collision if (ball.getPosition().x <= player1.getPosition().x + player1.getSize().x) { if ((ball.getPosition().y + ballDiameter >= player1.getPosition().y && ball.getPosition().y + ballDiameter <= player1.getPosition().y + player1.getSize().y) || ball.getPosition().y <= player1.getPosition().y + player1.getSize().y && ball.getPosition().y >= player1.getPosition().y) { ballVelX = (ballVelX - 1) * -1; bounce.play(); } else { point.play(); player2Score += 1; ballX = RENDERWIDTH / 2 - ball.getRadius(); if (BALLSPEED < 8) BALLSPEED += 0.5; ballVelX = BALLSPEED; score2.setString(convertInt(player2Score)); score2.setPosition(3 * RENDERWIDTH / 4 - score2.getLocalBounds().width, 0); if (p2Len > 30) p2Len -= 10; player2.setSize(sf::Vector2f(10, p2Len)); if (p1Len < 80) p1Len += 10; player1.setSize(sf::Vector2f(10, p1Len)); } } //ball and player 2 collision if (ball.getPosition().x + ballDiameter >= player2.getPosition().x) { if ((ball.getPosition().y + ballDiameter >= player2.getPosition().y && ball.getPosition().y + ballDiameter <= player2.getPosition().y + player2.getSize().y) || ball.getPosition().y <= player2.getPosition().y + player2.getSize().y && ball.getPosition().y >= player2.getPosition().y) { ballVelX = (ballVelX + 1) * -1; bounce.play(); } else { point.play(); player1Score += 1; ballX = RENDERWIDTH / 2 - ball.getRadius(); if (BALLSPEED < 8) BALLSPEED += 0.5; ballVelX = -BALLSPEED; score1.setString(convertInt(player1Score)); if (p1Len > 30) p1Len -= 10; player1.setSize(sf::Vector2f(10, p1Len)); if (p2Len < 80) p2Len += 10; player2.setSize(sf::Vector2f(10, p2Len)); } } //ball position update ballX += ballVelX; ballY += ballVelY; ball.setPosition(ballX, ballY); //render updates pong.clear(); pong.draw(score1); pong.draw(timer1); pong.draw(timer2); pong.draw(score2); pong.draw(player1); pong.draw(player2); pong.draw(ball); pong.draw(ncp); pong.display(); while(player1Score + player2Score == 3) { if(player1Score > player2Score) timer1.setString(convertInt(time1 += 10000)); if(player1Score < player2Score) timer2.setString(convertInt(time2 += 10000)); pong.clear(sf::Color::Black); pong.draw(score1); pong.draw(timer1); pong.draw(timer2); pong.draw(score2); pong.draw(gameover); pong.display(); counter(3); break; } } std::stringstream ss; ss.str (timer1.getString()); std::string scorePlayer1 = ss.str(); ss.str (timer2.getString()); std::string scorePlayer2 = ss.str(); std::cout << "Final Score:" << '\n'; std::cout << "Player1: " + scorePlayer1 << '\n'; std::cout << "Player2: " + scorePlayer2 << '\n'; std::ofstream myfile ("highscores.txt", std::ofstream::in | std::ofstream::out | std::ofstream::app); if (myfile.is_open()) { myfile << scorePlayer1 << std::endl; myfile << scorePlayer2 << std::endl; myfile.close(); } else std::cout << "Unable to open file"; return 0; }
address JNI_FastGetField::generate_fast_get_int_field0(BasicType type) { const char *name; switch (type) { case T_BOOLEAN: name = "jni_fast_GetBooleanField"; break; case T_BYTE: name = "jni_fast_GetByteField"; break; case T_CHAR: name = "jni_fast_GetCharField"; break; case T_SHORT: name = "jni_fast_GetShortField"; break; case T_INT: name = "jni_fast_GetIntField"; break; default: ShouldNotReachHere(); } ResourceMark rm; BufferBlob* b = BufferBlob::create(name, BUFFER_SIZE*wordSize); address fast_entry = b->instructions_begin(); CodeBuffer cbuf(fast_entry, b->instructions_size()); MacroAssembler* masm = new MacroAssembler(&cbuf); Label slow; // stack layout: offset from rsp (in words): // return pc 0 // jni env 1 // obj 2 // jfieldID 3 ExternalAddress counter(SafepointSynchronize::safepoint_counter_addr()); __ mov32 (rcx, counter); __ testb (rcx, 1); __ jcc (Assembler::notZero, slow); if (os::is_MP()) { __ mov(rax, rcx); __ andptr(rax, 1); // rax, must end up 0 __ movptr(rdx, Address(rsp, rax, Address::times_1, 2*wordSize)); // obj, notice rax, is 0. // rdx is data dependent on rcx. } else { __ movptr (rdx, Address(rsp, 2*wordSize)); // obj } __ movptr(rax, Address(rsp, 3*wordSize)); // jfieldID __ movptr(rdx, Address(rdx, 0)); // *obj __ shrptr (rax, 2); // offset assert(count < LIST_CAPACITY, "LIST_CAPACITY too small"); speculative_load_pclist[count] = __ pc(); switch (type) { case T_BOOLEAN: __ movzbl (rax, Address(rdx, rax, Address::times_1)); break; case T_BYTE: __ movsbl (rax, Address(rdx, rax, Address::times_1)); break; case T_CHAR: __ movzwl (rax, Address(rdx, rax, Address::times_1)); break; case T_SHORT: __ movswl (rax, Address(rdx, rax, Address::times_1)); break; case T_INT: __ movl (rax, Address(rdx, rax, Address::times_1)); break; default: ShouldNotReachHere(); } Address ca1; if (os::is_MP()) { __ lea(rdx, counter); __ xorptr(rdx, rax); __ xorptr(rdx, rax); __ cmp32(rcx, Address(rdx, 0)); // ca1 is the same as ca because // rax, ^ counter_addr ^ rax, = address // ca1 is data dependent on rax,. } else { __ cmp32(rcx, counter); } __ jcc (Assembler::notEqual, slow); #ifndef _WINDOWS __ ret (0); #else // __stdcall calling convention __ ret (3*wordSize); #endif slowcase_entry_pclist[count++] = __ pc(); __ bind (slow); address slow_case_addr; switch (type) { case T_BOOLEAN: slow_case_addr = jni_GetBooleanField_addr(); break; case T_BYTE: slow_case_addr = jni_GetByteField_addr(); break; case T_CHAR: slow_case_addr = jni_GetCharField_addr(); break; case T_SHORT: slow_case_addr = jni_GetShortField_addr(); break; case T_INT: slow_case_addr = jni_GetIntField_addr(); } // tail call __ jump (ExternalAddress(slow_case_addr)); __ flush (); #ifndef _WINDOWS return fast_entry; #else switch (type) { case T_BOOLEAN: jni_fast_GetBooleanField_fp = (GetBooleanField_t)fast_entry; break; case T_BYTE: jni_fast_GetByteField_fp = (GetByteField_t)fast_entry; break; case T_CHAR: jni_fast_GetCharField_fp = (GetCharField_t)fast_entry; break; case T_SHORT: jni_fast_GetShortField_fp = (GetShortField_t)fast_entry; break; case T_INT: jni_fast_GetIntField_fp = (GetIntField_t)fast_entry; } return os::win32::fast_jni_accessor_wrapper(type); #endif }
void editfile (list_ref list) { char stdinline[1024]; int stdincount = 0; for(;; ++stdincount) { printf ("%s: ", Exec_Name); char *linepos = fgets (stdinline, sizeof stdinline, stdin); if(isspace(stdinline[0]) != 0) { continue; } if (linepos == NULL) break; if (want_echo) printf ("%s", stdinline); linepos = strchr (stdinline, '\n'); if (linepos == NULL || stdinline[0] == '\0') { badline (stdincount, stdinline); } else { *linepos = '\0'; switch (stdinline[0]) { case '$': setmove_list (list, MOVE_LAST); break; case '*': print_list(list); break; case '.': printf("%6d: %s\n",counter(list, curr), viewcurr_list (list)); break; case '0': setmove_list (list, MOVE_HEAD); break; case '<': setmove_list (list, MOVE_PREV); break; case '>': setmove_list (list, MOVE_NEXT); break; case '@': debugdump_list (list); break; case 'a': insertAfter(list, stdinline+1, curr); break; case 'd': delete_list (list); break; case 'i': insertBefore(list, stdinline+1); break; case 'r': putfilelist (list, stdinline+1, 0); break; case 'w': putfilelist (list, stdinline+1, 2); break; case '#': break; default : badline (stdincount, stdinline); } } } printf (" ^D\n"); }
bool dataAnalysis::doAnalysis() { bool rval = false; this->deleteDataBase(); //! load the database this->_writeCounts = true; this->_progress = 0; emit this->analysisStatus(QObject::tr("%1: reading database").arg(this->_projectName)); emit this->analysisProgress(this->_progress); this->_dataBase = new database(this->_headers, this->_indexStepSize); this->_dataBase->readData(this->_dataBaseInfile); this->_dataBasePresent = true; this->_progress += 1; //! initialize everything emit this->analysisStatus(QObject::tr("%1: starting threads").arg(this->_projectName)); emit this->analysisProgress(this->_progress); // open a bamhandler as reader bamHandler producer(this->_readsInfile, this->_readsOutfile, QString("r"), &this->_bufferSizeBAM, &this->_bufferBAM, &this->_bufferIsNotFullBAM, &this->_bufferIsNotEmptyBAM, &this->_mutexBAM, &this->_usedSpaceBAM, this->_useRegion, this->_regionStartName, this->_regionStart, this->_regionEndName, this->_regionEnd); // initialize the readmapper readMapper mapper(&this->_bufferSizeBAM, &this->_bufferBAM, &this->_bufferIsNotFullBAM, &this->_bufferIsNotEmptyBAM, &this->_mutexBAM, &this->_usedSpaceBAM, &this->_bufferSizeMAP, &this->_bufferMAP, &this->_bufferIsNotFullMAP, &this->_bufferIsNotEmptyMAP, &this->_mutexMAP, &this->_usedSpaceMAP, this->_dataBase, this->_stranded, this->_antisense, this->_useMulti); // initialize the readcounter readCounter counter(&this->_bufferSizeMAP, &this->_bufferMAP, &this->_bufferIsNotFullMAP, &this->_bufferIsNotEmptyMAP, &this->_mutexMAP, &this->_usedSpaceMAP, &this->_bufferSizeOUT, &this->_bufferOUT, &this->_bufferIsNotFullOUT, &this->_bufferIsNotEmptyOUT, &this->_mutexOUT, &this->_usedSpaceOUT, this->_dataBase, this->_minReads, this->_maxDist, this->_minBelowMaxDist); // open a bamwriter bamHandler consumer(this->_readsInfile, this->_readsOutfile, QString("w"), &this->_bufferSizeOUT, &this->_bufferOUT, &this->_bufferIsNotFullOUT, &this->_bufferIsNotEmptyOUT, &this->_mutexOUT, &this->_usedSpaceOUT, this->_useRegion, this->_regionStartName, this->_regionStart, this->_regionEndName, this->_regionEnd); //! set the connections from this thread to the others (if run is canceled) //! hm - stopping them in parallel does not really work... is not implemented at the moment // at the moment all producers simply empty their buffer and exit. This should trigger the consumers to follow connect(this, SIGNAL(stopThreads()), &producer, SLOT(runCanceled()), Qt::DirectConnection); //! NOTE THAT THE OTHER ONES WILL KEEP ON GOING UNTIL BUFFERS ARE EMPTY //connect(this, SIGNAL(stopThreads()), &mapper, SLOT(runCanceled()), Qt::DirectConnection); // not necessary //connect(this, SIGNAL(stopThreads()), &counter, SLOT(runCanceled()), Qt::DirectConnection); // not necessary //connect(this, SIGNAL(stopThreads()), &consumer, SLOT(runCanceled()), Qt::DirectConnection); // not necessary //! set the connections NOTE: if this is not a QThread, use QObject::connect() connect(&producer, SIGNAL(finished()), &mapper, SLOT(producerFinished()), Qt::DirectConnection); connect(&mapper, SIGNAL(finished()), &counter, SLOT(producersAreFinished()), Qt::DirectConnection); // direct connection as we have only one mapper connect(&counter, SIGNAL(finished()), &consumer, SLOT(producerFinished()), Qt::DirectConnection); //! signal this->_progress += 1; emit this->analysisStatus(QObject::tr("%1: setting up").arg(this->_projectName)); emit this->analysisProgress(this->_progress); //! count the number of lines this->_numLines = producer.getNumberLines(); //! connect the processed lines counters (only the writer) //connect(this->_producer, SIGNAL(xLinesProcessed(int)), this, SLOT(readerLines(int)), Qt::DirectConnection); connect(&consumer, SIGNAL(xLinesProcessed(int)), this, SLOT(writerLines(int)), Qt::DirectConnection); //! connect the stats (only the writer) //connect(&producer, SIGNAL(statsObtained(QString)), this, SLOT(readerStats(QString)), Qt::DirectConnection); connect(&consumer, SIGNAL(statsObtained(QString)), this, SLOT(writerStats(QString)), Qt::DirectConnection); //! signal this->_progress += 1; emit this->analysisStatus(QObject::tr("%1: processing").arg(this->_projectName)); emit this->analysisProgress(this->_progress); //! start the threads producer.start(); mapper.start(); counter.start(); consumer.start(); //! wait for them producer.wait(); mapper.wait(); counter.wait(); consumer.wait(); //! write the table with the counts if (this->_writeCounts) { rval = this->_dataBase->writeCountTable(this->_countTableFile); emit this->analysisCountsWritten(this->_countTableFile); this->_progress = 100; emit this->analysisStatus(QObject::tr("%1: finished").arg(this->_projectName)); emit this->analysisProgress(this->_progress); } this->deleteDataBase(); emit this->idleAgain(); //! return return(rval); }
std::string AbstractConfiguration::internalExpand(const std::string& value) const { AutoCounter counter(_depth); if (_depth > 10) throw CircularReferenceException("Too many property references encountered"); return uncheckedExpand(value); }
bool Uploader::uploadList(list<string> List, string collection) { if(List.empty()) { cout << "Empty list!" << endl; return 0; } missedFiles = 0; mongo::GridFS fs = mongo::GridFS(conn,dbName.c_str(),collection.c_str()); files = fs.list(); while(files.get()->more()){ mongo::GridFile file = fs.findFile(files.get()->next()); hashlist.emplace_front(boost::algorithm::to_upper_copy(file.getMD5())); } for(list<string>::iterator it = List.begin(); it != List.end(); ++it) { p = *it; ifstream counter(*it); counter.seekg(0,ios::end); if(boost::filesystem::exists(p)) { getHash(); hashIter = find(hashlist.begin(),hashlist.end(),digest); if(hashIter == hashlist.end()){ masterList.emplace_back(*it,counter.tellg()); total += counter.tellg(); } else{ missedList.emplace_back(*it,counter.tellg()); ++missedFiles; } } } hashlist.clear(); meter.reset(total,1,1); masterList.sort(low_to_high); if(!masterList.empty()) for(auto it:masterList){ p = it.first; if(boost::filesystem::exists(p)){ fs.storeFile(it.first,p.filename().string()); meter.hit(it.second); } else { missedList.push_back(it); ++missedFiles; } } else { cout << "All matching files are already in database." << endl; cout << "Files were not uploaded: " << endl; for(auto it:missedList) cout << it.first << ": " << it.second << " bytes" << endl; return true; } if(missedFiles >= 1){ cout << "Some files were not uploaded:" << endl; for(auto it:missedList) cout << it.first << ": " << it.second << " bytes" << endl; return 0; } meter.finished(); masterList.clear(); total = 0; return 1; }
const Ordinal nextCounter() const { assert(counter() < 0xffff); return Ordinal(_ordinal+((uint64_t)1<<0)); }
/* * thread_switch: * * Context switch. User may supply thread hint. * * Fixed priority threads that call this get what they asked for * even if that violates priority order. */ kern_return_t thread_switch( mach_port_t thread_name, int option, mach_msg_timeout_t option_time) { thread_t cur_thread = current_thread(); processor_t myprocessor; ipc_port_t port; /* * Process option. */ switch (option) { case SWITCH_OPTION_NONE: /* * Nothing to do. */ break; case SWITCH_OPTION_DEPRESS: /* * Depress priority for given time. */ thread_depress_priority(cur_thread, option_time); break; case SWITCH_OPTION_WAIT: thread_will_wait_with_timeout(cur_thread, option_time); break; default: return(KERN_INVALID_ARGUMENT); } #ifndef MIGRATING_THREADS /* XXX thread_run defunct */ /* * Check and act on thread hint if appropriate. */ if ((thread_name != 0) && (ipc_port_translate_send(cur_thread->task->itk_space, thread_name, &port) == KERN_SUCCESS)) { /* port is locked, but it might not be active */ /* * Get corresponding thread. */ if (ip_active(port) && (ip_kotype(port) == IKOT_THREAD)) { thread_t thread; spl_t s; thread = (thread_t) port->ip_kobject; /* * Check if the thread is in the right pset. Then * pull it off its run queue. If it * doesn't come, then it's not eligible. */ s = splsched(); thread_lock(thread); if ((thread->processor_set == cur_thread->processor_set) && (rem_runq(thread) != RUN_QUEUE_NULL)) { /* * Hah, got it!! */ thread_unlock(thread); (void) splx(s); ip_unlock(port); /* XXX thread might disappear on us now? */ #if MACH_FIXPRI if (thread->policy == POLICY_FIXEDPRI) { myprocessor = current_processor(); myprocessor->quantum = thread->sched_data; myprocessor->first_quantum = TRUE; } #endif /* MACH_FIXPRI */ counter(c_thread_switch_handoff++); thread_run(thread_switch_continue, thread); /* * Restore depressed priority */ if (cur_thread->depress_priority >= 0) (void) thread_depress_abort(cur_thread); return(KERN_SUCCESS); } thread_unlock(thread); (void) splx(s); } ip_unlock(port); } #endif /* not MIGRATING_THREADS */ /* * No handoff hint supplied, or hint was wrong. Call thread_block() in * hopes of running something else. If nothing else is runnable, * thread_block will detect this. WARNING: thread_switch with no * option will not do anything useful if the thread calling it is the * highest priority thread (can easily happen with a collection * of timesharing threads). */ #if NCPUS > 1 myprocessor = current_processor(); if (myprocessor->processor_set->runq.count > 0 || myprocessor->runq.count > 0) #endif /* NCPUS > 1 */ { counter(c_thread_switch_block++); thread_block(thread_switch_continue); } /* * Restore depressed priority */ if (cur_thread->depress_priority >= 0) (void) thread_depress_abort(cur_thread); return(KERN_SUCCESS); }
void exception_raise( ipc_port_t dest_port, ipc_port_t thread_port, ipc_port_t task_port, integer_t _exception, integer_t code, integer_t subcode) { ipc_thread_t self = current_thread(); ipc_thread_t receiver; ipc_port_t reply_port; ipc_mqueue_t dest_mqueue; ipc_mqueue_t reply_mqueue; ipc_kmsg_t kmsg; mach_msg_return_t mr; assert(IP_VALID(dest_port)); /* * We will eventually need a message buffer. * Grab the buffer now, while nothing is locked. * This buffer will get handed to the exception server, * and it will give the buffer back with its reply. */ kmsg = ikm_cache(); if (kmsg != IKM_NULL) { ikm_cache() = IKM_NULL; ikm_check_initialized(kmsg, IKM_SAVED_KMSG_SIZE); } else { kmsg = ikm_alloc(IKM_SAVED_MSG_SIZE); if (kmsg == IKM_NULL) panic("exception_raise"); ikm_init(kmsg, IKM_SAVED_MSG_SIZE); } /* * We need a reply port for the RPC. * Check first for a cached port. */ ith_lock(self); assert(self->ith_self != IP_NULL); reply_port = self->ith_rpc_reply; if (reply_port == IP_NULL) { ith_unlock(self); reply_port = ipc_port_alloc_reply(); ith_lock(self); if ((reply_port == IP_NULL) || (self->ith_rpc_reply != IP_NULL)) panic("exception_raise"); self->ith_rpc_reply = reply_port; } ip_lock(reply_port); assert(ip_active(reply_port)); ith_unlock(self); /* * Make a naked send-once right for the reply port, * to hand to the exception server. * Make an extra reference for the reply port, * to receive on. This protects us against * mach_msg_abort_rpc. */ reply_port->ip_sorights++; ip_reference(reply_port); ip_reference(reply_port); self->ith_port = reply_port; reply_mqueue = &reply_port->ip_messages; imq_lock(reply_mqueue); assert(ipc_kmsg_queue_empty(&reply_mqueue->imq_messages)); ip_unlock(reply_port); /* * Make sure we can queue to the destination port. */ if (!ip_lock_try(dest_port)) { imq_unlock(reply_mqueue); goto slow_exception_raise; } if (!ip_active(dest_port) || (dest_port->ip_receiver == ipc_space_kernel)) { imq_unlock(reply_mqueue); ip_unlock(dest_port); goto slow_exception_raise; } /* * Find the destination message queue. */ { ipc_pset_t dest_pset; dest_pset = dest_port->ip_pset; if (dest_pset == IPS_NULL) dest_mqueue = &dest_port->ip_messages; else dest_mqueue = &dest_pset->ips_messages; } if (!imq_lock_try(dest_mqueue)) { imq_unlock(reply_mqueue); ip_unlock(dest_port); goto slow_exception_raise; } /* * Safe to unlock dest_port, because we hold * dest_mqueue locked. We never bother changing * dest_port->ip_msgcount. */ ip_unlock(dest_port); receiver = ipc_thread_queue_first(&dest_mqueue->imq_threads); if ((receiver == ITH_NULL) || !((receiver->swap_func == (void (*)()) mach_msg_continue) || ((receiver->swap_func == (void (*)()) mach_msg_receive_continue) && (sizeof(struct mach_exception) <= receiver->ith_msize) && ((receiver->ith_option & MACH_RCV_NOTIFY) == 0))) || !thread_handoff(self, exception_raise_continue, receiver)) { imq_unlock(reply_mqueue); imq_unlock(dest_mqueue); goto slow_exception_raise; } counter(c_exception_raise_block++); assert(current_thread() == receiver); /* * We need to finish preparing self for its * time asleep in reply_mqueue. self is left * holding the extra ref for reply_port. */ ipc_thread_enqueue_macro(&reply_mqueue->imq_threads, self); self->ith_state = MACH_RCV_IN_PROGRESS; self->ith_msize = MACH_MSG_SIZE_MAX; imq_unlock(reply_mqueue); /* * Finish extracting receiver from dest_mqueue. */ ipc_thread_rmqueue_first_macro( &dest_mqueue->imq_threads, receiver); imq_unlock(dest_mqueue); /* * Release the receiver's reference for his object. */ { ipc_object_t object = receiver->ith_object; io_lock(object); io_release(object); io_check_unlock(object); } { struct mach_exception *exc = (struct mach_exception *) &kmsg->ikm_header; ipc_space_t space = receiver->task->itk_space; /* * We are running as the receiver now. We hold * the following resources, which must be consumed: * kmsg, send-once right for reply_port * send rights for dest_port, thread_port, task_port * Synthesize a kmsg for copyout to the receiver. */ exc->Head.msgh_bits = (MACH_MSGH_BITS(MACH_MSG_TYPE_PORT_SEND_ONCE, MACH_MSG_TYPE_PORT_SEND) | MACH_MSGH_BITS_COMPLEX); exc->Head.msgh_size = sizeof *exc; /* exc->Head.msgh_remote_port later */ /* exc->Head.msgh_local_port later */ exc->Head.msgh_seqno = 0; exc->Head.msgh_id = MACH_EXCEPTION_ID; exc->threadType = exc_port_proto; /* exc->thread later */ exc->taskType = exc_port_proto; /* exc->task later */ exc->exceptionType = exc_code_proto; exc->exception = _exception; exc->codeType = exc_code_proto; exc->code = code; exc->subcodeType = exc_code_proto; exc->subcode = subcode; /* * Check that the receiver can handle the message. */ if (receiver->ith_rcv_size < sizeof(struct mach_exception)) { /* * ipc_kmsg_destroy is a handy way to consume * the resources we hold, but it requires setup. */ exc->Head.msgh_bits = (MACH_MSGH_BITS(MACH_MSG_TYPE_PORT_SEND, MACH_MSG_TYPE_PORT_SEND_ONCE) | MACH_MSGH_BITS_COMPLEX); exc->Head.msgh_remote_port = (mach_port_t) dest_port; exc->Head.msgh_local_port = (mach_port_t) reply_port; exc->thread = (mach_port_t) thread_port; exc->task = (mach_port_t) task_port; ipc_kmsg_destroy(kmsg); thread_syscall_return(MACH_RCV_TOO_LARGE); /*NOTREACHED*/ } is_write_lock(space); assert(space->is_active); /* * To do an atomic copyout, need simultaneous * locks on both ports and the space. */ ip_lock(dest_port); if (!ip_active(dest_port) || !ip_lock_try(reply_port)) { abort_copyout: ip_unlock(dest_port); is_write_unlock(space); /* * Oh well, we have to do the header the slow way. * First make it look like it's in-transit. */ exc->Head.msgh_bits = (MACH_MSGH_BITS(MACH_MSG_TYPE_PORT_SEND, MACH_MSG_TYPE_PORT_SEND_ONCE) | MACH_MSGH_BITS_COMPLEX); exc->Head.msgh_remote_port = (mach_port_t) dest_port; exc->Head.msgh_local_port = (mach_port_t) reply_port; mr = ipc_kmsg_copyout_header(&exc->Head, space, MACH_PORT_NULL); if (mr == MACH_MSG_SUCCESS) goto copyout_body; /* * Ack! Prepare for ipc_kmsg_copyout_dest. * It will consume thread_port and task_port. */ exc->thread = (mach_port_t) thread_port; exc->task = (mach_port_t) task_port; ipc_kmsg_copyout_dest(kmsg, space); (void) ipc_kmsg_put(receiver->ith_msg, kmsg, sizeof(mach_msg_header_t)); thread_syscall_return(mr); /*NOTREACHED*/ } if (!ip_active(reply_port)) { ip_unlock(reply_port); goto abort_copyout; } assert(reply_port->ip_sorights > 0); ip_unlock(reply_port); { kern_return_t kr; ipc_entry_t entry; kr = ipc_entry_get (space, &exc->Head.msgh_remote_port, &entry); if (kr) goto abort_copyout; { mach_port_gen_t gen; assert((entry->ie_bits &~ IE_BITS_GEN_MASK) == 0); gen = entry->ie_bits + IE_BITS_GEN_ONE; /* optimized ipc_right_copyout */ entry->ie_bits = gen | (MACH_PORT_TYPE_SEND_ONCE | 1); } entry->ie_object = (ipc_object_t) reply_port; is_write_unlock(space); } /* optimized ipc_object_copyout_dest */ assert(dest_port->ip_srights > 0); ip_release(dest_port); exc->Head.msgh_local_port = ((dest_port->ip_receiver == space) ? dest_port->ip_receiver_name : MACH_PORT_NULL); if ((--dest_port->ip_srights == 0) && (dest_port->ip_nsrequest != IP_NULL)) { ipc_port_t nsrequest; mach_port_mscount_t mscount; /* a rather rare case */ nsrequest = dest_port->ip_nsrequest; mscount = dest_port->ip_mscount; dest_port->ip_nsrequest = IP_NULL; ip_unlock(dest_port); ipc_notify_no_senders(nsrequest, mscount); } else ip_unlock(dest_port); copyout_body: /* * Optimized version of ipc_kmsg_copyout_body, * to handle the two ports in the body. */ mr = (ipc_kmsg_copyout_object(space, (ipc_object_t) thread_port, MACH_MSG_TYPE_PORT_SEND, &exc->thread) | ipc_kmsg_copyout_object(space, (ipc_object_t) task_port, MACH_MSG_TYPE_PORT_SEND, &exc->task)); if (mr != MACH_MSG_SUCCESS) { (void) ipc_kmsg_put(receiver->ith_msg, kmsg, kmsg->ikm_header.msgh_size); thread_syscall_return(mr | MACH_RCV_BODY_ERROR); /*NOTREACHED*/ } } /* * Optimized version of ipc_kmsg_put. * We must check ikm_cache after copyoutmsg. */ ikm_check_initialized(kmsg, kmsg->ikm_size); assert(kmsg->ikm_size == IKM_SAVED_KMSG_SIZE); if (copyoutmsg(&kmsg->ikm_header, receiver->ith_msg, sizeof(struct mach_exception)) || (ikm_cache() != IKM_NULL)) { mr = ipc_kmsg_put(receiver->ith_msg, kmsg, kmsg->ikm_header.msgh_size); thread_syscall_return(mr); /*NOTREACHED*/ } ikm_cache() = kmsg; thread_syscall_return(MACH_MSG_SUCCESS); /*NOTREACHED*/ #ifndef __GNUC__ return; /* help for the compiler */ #endif slow_exception_raise: { struct mach_exception *exc = (struct mach_exception *) &kmsg->ikm_header; ipc_kmsg_t reply_kmsg; mach_port_seqno_t reply_seqno; exception_raise_misses++; /* * We hold the following resources, which must be consumed: * kmsg, send-once right and ref for reply_port * send rights for dest_port, thread_port, task_port * Synthesize a kmsg to send. */ exc->Head.msgh_bits = (MACH_MSGH_BITS(MACH_MSG_TYPE_PORT_SEND, MACH_MSG_TYPE_PORT_SEND_ONCE) | MACH_MSGH_BITS_COMPLEX); exc->Head.msgh_size = sizeof *exc; exc->Head.msgh_remote_port = (mach_port_t) dest_port; exc->Head.msgh_local_port = (mach_port_t) reply_port; exc->Head.msgh_seqno = 0; exc->Head.msgh_id = MACH_EXCEPTION_ID; exc->threadType = exc_port_proto; exc->thread = (mach_port_t) thread_port; exc->taskType = exc_port_proto; exc->task = (mach_port_t) task_port; exc->exceptionType = exc_code_proto; exc->exception = _exception; exc->codeType = exc_code_proto; exc->code = code; exc->subcodeType = exc_code_proto; exc->subcode = subcode; ipc_mqueue_send_always(kmsg); /* * We are left with a ref for reply_port, * which we use to receive the reply message. */ ip_lock(reply_port); if (!ip_active(reply_port)) { ip_unlock(reply_port); exception_raise_continue_slow(MACH_RCV_PORT_DIED, IKM_NULL, /*dummy*/0); /*NOTREACHED*/ } imq_lock(reply_mqueue); ip_unlock(reply_port); mr = ipc_mqueue_receive(reply_mqueue, MACH_MSG_OPTION_NONE, MACH_MSG_SIZE_MAX, MACH_MSG_TIMEOUT_NONE, FALSE, exception_raise_continue, &reply_kmsg, &reply_seqno); /* reply_mqueue is unlocked */ exception_raise_continue_slow(mr, reply_kmsg, reply_seqno); /*NOTREACHED*/ } }
void MyKmeans(Mat& mat, int nc, Mat& out_centmat, Mat& out_idxmat) { /* 1. Initialization*/ srand(time(NULL)); int *matIndex = new int[mat.rows]; for(int i = 0; i < mat.rows; ++i) matIndex[i] = 1; for(int i = 0; i< nc; i++){ int tmp; do{ tmp = rand()%mat.rows; } while(!matIndex[tmp]); cout <<tmp <<endl; mat.row(tmp).copyTo(out_centmat.row(i)); matIndex[tmp] = 0; } /* Loop!*/ Mat counter(out_centmat.rows, 1, CV_32SC1); for(int t = 0; t < NumIterations; t++){ /*2. Assigment*/ for(int i = 0; i< mat.rows; i++){ double minDistance = norm(mat.row(i)-out_centmat.row(0)); int minIndex = 0; for(int k = 1; k< nc; k++){ float d = norm(mat.row(i)-out_centmat.row(k)); if(d <minDistance){ minIndex = k; minDistance = d; } } out_idxmat.at<int>(i,0) = minIndex; } /*3. Update*/ for(int i = 0; i<counter.rows; i++){ counter.at<float>(i,0) = 0; } for(int i = 0; i <out_centmat.rows; i++){ for(int j = 0; j <out_centmat.cols; j++){ out_centmat.at<float>(i,j) = 0; } } for(int i=0; i<mat.rows; i++){ out_centmat.row(out_idxmat.at<int>(i,0)) +=mat.row(i); cout << counter.at<int>(out_idxmat.at<int>(i,0),0)++<<endl; } cout <<counter.at<int>(0,0)<<endl; cout <<counter.at<int>(1,0)<<endl; cout <<out_centmat.row(0)<<endl; cout <<out_centmat.row(1)<<endl; out_centmat.row(0) = out_centmat.row(0)/counter.at<int>(0,0); out_centmat.row(1) = out_centmat.row(1)/counter.at<int>(1,0); } }
static ManagerId id() { static ManagerId id = counter()++; return id; }
void test_shared_alloc() { #if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST ) typedef const Kokkos::Impl::SharedAllocationHeader Header; typedef Kokkos::Impl::SharedAllocationTracker Tracker; typedef Kokkos::Impl::SharedAllocationRecord< void, void > RecordBase; typedef Kokkos::Impl::SharedAllocationRecord< MemorySpace, void > RecordMemS; typedef Kokkos::Impl::SharedAllocationRecord< MemorySpace, SharedAllocDestroy > RecordFull; static_assert( sizeof( Tracker ) == sizeof( int* ), "SharedAllocationTracker has wrong size!" ); MemorySpace s; const size_t N = 1200; const size_t size = 8; RecordMemS * rarray[ N ]; Header * harray[ N ]; RecordMemS ** const r = rarray; Header ** const h = harray; Kokkos::RangePolicy< ExecutionSpace > range( 0, N ); { // Since always executed on host space, leave [=] Kokkos::parallel_for( range, [=] ( size_t i ) { char name[64]; sprintf( name, "test_%.2d", int( i ) ); r[i] = RecordMemS::allocate( s, name, size * ( i + 1 ) ); h[i] = Header::get_header( r[i]->data() ); ASSERT_EQ( r[i]->use_count(), 0 ); for ( size_t j = 0; j < ( i / 10 ) + 1; ++j ) RecordBase::increment( r[i] ); ASSERT_EQ( r[i]->use_count(), ( i / 10 ) + 1 ); ASSERT_EQ( r[i], RecordMemS::get_record( r[i]->data() ) ); }); #ifdef KOKKOS_DEBUG // Sanity check for the whole set of allocation records to which this record belongs. RecordBase::is_sane( r[0] ); // RecordMemS::print_records( std::cout, s, true ); #endif Kokkos::parallel_for( range, [=] ( size_t i ) { while ( 0 != ( r[i] = static_cast< RecordMemS * >( RecordBase::decrement( r[i] ) ) ) ) { #ifdef KOKKOS_DEBUG if ( r[i]->use_count() == 1 ) RecordBase::is_sane( r[i] ); #endif } }); } { int destroy_count = 0; SharedAllocDestroy counter( &destroy_count ); Kokkos::parallel_for( range, [=] ( size_t i ) { char name[64]; sprintf( name, "test_%.2d", int( i ) ); RecordFull * rec = RecordFull::allocate( s, name, size * ( i + 1 ) ); rec->m_destroy = counter; r[i] = rec; h[i] = Header::get_header( r[i]->data() ); ASSERT_EQ( r[i]->use_count(), 0 ); for ( size_t j = 0; j < ( i / 10 ) + 1; ++j ) RecordBase::increment( r[i] ); ASSERT_EQ( r[i]->use_count(), ( i / 10 ) + 1 ); ASSERT_EQ( r[i], RecordMemS::get_record( r[i]->data() ) ); }); #ifdef KOKKOS_DEBUG RecordBase::is_sane( r[0] ); #endif Kokkos::parallel_for( range, [=] ( size_t i ) { while ( 0 != ( r[i] = static_cast< RecordMemS * >( RecordBase::decrement( r[i] ) ) ) ) { #ifdef KOKKOS_DEBUG if ( r[i]->use_count() == 1 ) RecordBase::is_sane( r[i] ); #endif } }); ASSERT_EQ( destroy_count, int( N ) ); } { int destroy_count = 0; { RecordFull * rec = RecordFull::allocate( s, "test", size ); // ... Construction of the allocated { rec->data(), rec->size() } // Copy destruction function object into the allocation record. rec->m_destroy = SharedAllocDestroy( & destroy_count ); ASSERT_EQ( rec->use_count(), 0 ); // Start tracking, increments the use count from 0 to 1. Tracker track; track.assign_allocated_record_to_uninitialized( rec ); ASSERT_EQ( rec->use_count(), 1 ); ASSERT_EQ( track.use_count(), 1 ); // Verify construction / destruction increment. for ( size_t i = 0; i < N; ++i ) { ASSERT_EQ( rec->use_count(), 1 ); { Tracker local_tracker; local_tracker.assign_allocated_record_to_uninitialized( rec ); ASSERT_EQ( rec->use_count(), 2 ); ASSERT_EQ( local_tracker.use_count(), 2 ); } ASSERT_EQ( rec->use_count(), 1 ); ASSERT_EQ( track.use_count(), 1 ); } Kokkos::parallel_for( range, [=] ( size_t i ) { Tracker local_tracker; local_tracker.assign_allocated_record_to_uninitialized( rec ); ASSERT_GT( rec->use_count(), 1 ); }); ASSERT_EQ( rec->use_count(), 1 ); ASSERT_EQ( track.use_count(), 1 ); // Destruction of 'track' object deallocates the 'rec' and invokes the destroy function object. } ASSERT_EQ( destroy_count, 1 ); } #endif /* #if defined( KOKKOS_ACTIVE_EXECUTION_MEMORY_SPACE_HOST ) */ }
/* * Routine: ipc_mqueue_send * Purpose: * Send a message to a message queue. The message holds a reference * for the destination port for this message queue in the * msgh_remote_port field. * * If unsuccessful, the caller still has possession of * the message and must do something with it. If successful, * the message is queued, given to a receiver, or destroyed. * Conditions: * Nothing locked. * Returns: * MACH_MSG_SUCCESS The message was accepted. * MACH_SEND_TIMED_OUT Caller still has message. * MACH_SEND_INTERRUPTED Caller still has message. */ mach_msg_return_t ipc_mqueue_send( ipc_mqueue_t mqueue, ipc_kmsg_t kmsg, mach_msg_option_t option, mach_msg_timeout_t send_timeout, spl_t s) { int wresult; /* * Don't block if: * 1) We're under the queue limit. * 2) Caller used the MACH_SEND_ALWAYS internal option. * 3) Message is sent to a send-once right. */ if (!imq_full(mqueue) || (!imq_full_kernel(mqueue) && ((option & MACH_SEND_ALWAYS) || (MACH_MSGH_BITS_REMOTE(kmsg->ikm_header->msgh_bits) == MACH_MSG_TYPE_PORT_SEND_ONCE)))) { mqueue->imq_msgcount++; assert(mqueue->imq_msgcount > 0); imq_unlock(mqueue); splx(s); } else { thread_t cur_thread = current_thread(); uint64_t deadline; /* * We have to wait for space to be granted to us. */ if ((option & MACH_SEND_TIMEOUT) && (send_timeout == 0)) { imq_unlock(mqueue); splx(s); return MACH_SEND_TIMED_OUT; } if (imq_full_kernel(mqueue)) { imq_unlock(mqueue); splx(s); return MACH_SEND_NO_BUFFER; } mqueue->imq_fullwaiters = TRUE; thread_lock(cur_thread); if (option & MACH_SEND_TIMEOUT) clock_interval_to_deadline(send_timeout, 1000*NSEC_PER_USEC, &deadline); else deadline = 0; wresult = wait_queue_assert_wait64_locked( &mqueue->imq_wait_queue, IPC_MQUEUE_FULL, THREAD_ABORTSAFE, deadline, cur_thread); thread_unlock(cur_thread); imq_unlock(mqueue); splx(s); if (wresult == THREAD_WAITING) { wresult = thread_block(THREAD_CONTINUE_NULL); counter(c_ipc_mqueue_send_block++); } switch (wresult) { case THREAD_TIMED_OUT: assert(option & MACH_SEND_TIMEOUT); return MACH_SEND_TIMED_OUT; case THREAD_AWAKENED: /* we can proceed - inherited msgcount from waker */ assert(mqueue->imq_msgcount > 0); break; case THREAD_INTERRUPTED: return MACH_SEND_INTERRUPTED; case THREAD_RESTART: /* mqueue is being destroyed */ return MACH_SEND_INVALID_DEST; default: panic("ipc_mqueue_send"); } } ipc_mqueue_post(mqueue, kmsg); return MACH_MSG_SUCCESS; }
void GatherFolderImg::computeMask( bool save_counter ) { _mask = arma::zeros< arma::Mat< arma::u8 > >( _scene->n_rows, _scene->n_cols ) ; if ( _minFrequencyMask > 100 ) { _mask = 1 - _mask ; return ; } arma::Mat< arma::u16 > counter = arma::zeros< arma::Mat< arma::u16 > > ( _scene->n_rows, _scene->n_cols ) ; int x, y, slice, u ; boost::filesystem::path filePath; Pgm3dFactory<arma::u8> factory ; if ( _scene->max() == 0 ) { std::cerr<<"loop on slices"<<std::endl; for ( slice = 0 ; slice < _scene->n_slices ; slice++ ) { filePath = _folderpath ; filePath /= QString( ANTHILL_SLICE_NAME ).arg( slice, 0, 10 ).toStdString() ; BillonTpl<arma::u8> *image = factory.read( QString( filePath.string().c_str() ) ); *image *= -1 ; for ( y = 0 ; y < counter.n_rows ; y++ ) for ( x = 0 ; x < counter.n_cols ; x++ ) counter( y, x ) += (*image)( y,x,0 ) ; delete image ; } } else { for ( slice = 0 ; slice < _scene->n_slices ; slice++ ) { arma::Mat< arma::u8 > image = _scene->slice( slice ) ; arma::Mat< arma::u8 >::iterator readIter, readEnd = image.end() ; arma::Mat< arma::u16 >::iterator writeIter = counter.begin(); for ( readIter = image.begin() ; readIter != readEnd ; readIter++,writeIter++ ) *writeIter += *readIter ; } } if ( save_counter ) { arma::Cube<arma::u16> counter3D( counter.n_rows, counter.n_cols, 1 ) ; counter3D.slice(0) = counter ; counter3D.slice(0) *= 255 ; counter3D.slice(0) /= _scene->n_slices ; fs::path premaskfs = _folderpath ; premaskfs /= ANTHILL_PRE_MASK_NAME ; IOPgm3d<arma::u16,qint8,false>::write( counter3D, QString("%1").arg( premaskfs.string().c_str() ) ); } arma::u16 th = (_scene->n_slices*_minFrequencyMask)/100 ; for ( y = 0 ; y < _mask.n_rows ; y++ ) for ( x = 0 ; x < _mask.n_cols ; x++ ) if ( counter( y, x ) >= th ) _mask( y, x ) = 1 ; arma::Mat<arma::u8> *dilMask = dilate( _mask, 4, 4 ) ; _mask = *dilMask ; delete dilMask ; int minDist[] = { 0,0,0,0 } ; for ( y = 0 ; y < _mask.n_rows ; y++ ) for ( x = 0 ; x < _mask.n_cols ; x++ ) { if ( _mask(y,x) == 0 ) continue ; minDist[0] = std::max( minDist[0], x ) ; minDist[1] = std::max( minDist[1], y ) ; minDist[2] = std::max( minDist[2], (int)_mask.n_cols-x ) ; minDist[3] = std::max( minDist[3], (int)_mask.n_rows-y ) ; } if ( std::min( minDist[0], minDist[2] ) < std::min( minDist[1], minDist[3] ) ) { // the stand is either at the left or the right side if ( minDist[0] < minDist[2] ) { // left side for ( y = 0 ; y < _mask.n_rows ; y++ ) for ( x = _mask.n_cols-1 ; x >= 0 ; x-- ) { if ( _mask(y,x) == 0 ) continue ; for ( u = 0 ; u < x ; u++ ) _mask(y,u) = 1 ; break ; } } else { // right side for ( y = 0 ; y < _mask.n_rows ; y++ ) for ( x = 0 ; x < _mask.n_cols ; x++ ) { if ( _mask(y,x) == 0 ) continue ; for ( u = x ; u < _mask.n_cols ; u++ ) _mask(y,u) = 1 ; break ; } } } else { // the stand is either at the top or the bottom side if ( minDist[1] < minDist[3] ) { // top side for ( x = 0 ; x < _mask.n_cols ; x++ ) for ( y = _mask.n_rows-1 ; y >= 0 ; y-- ) { if ( _mask(y,x) == 0 ) continue ; for ( u = 0 ; u < y ; u++ ) _mask(u,x) = 1 ; break ; } } else { // bottom side for ( x = 0 ; x < _mask.n_cols ; x++ ) for ( y = 0 ; y < _mask.n_rows ; y++ ) { if ( _mask(y,x) == 0 ) continue ; for ( u = y ; u < _mask.n_rows ; u++ ) _mask(u,x) = 1 ; break ; } } } _mask = 1 - _mask ; }
int main(int argc, char** argv) try { po::options_description desc("Required options"); desc.add_options() ("mpq", po::value<std::string>(), "the mpq to create") ("files", po::value<std::vector<std::string> >(), "input files"); po::positional_options_description p; p.add("mpq", 1); p.add("files", -1); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm); po::notify(vm); if (!vm.count("files") || !vm.count("mpq")) { std::cout << "usage: <mpq> [<files> ...]" << std::endl; return 1; } std::vector<std::string> files(vm["files"].as< std::vector<std::string> >()); std::vector<FileEntry> toAdd; fs::path mpqPath(vm["mpq"].as<std::string>()); for(std::vector<std::string>::iterator path = files.begin(); path != files.end(); ++path) { if(fs::is_regular_file(*path)) toAdd.push_back(FileEntry(*path, *path)); if(!fs::is_directory(*path)) //no symlinks etc continue; for(fs::recursive_directory_iterator file(*path), end; file != end; ++file) if(fs::is_regular_file(file->path())) toAdd.push_back(FileEntry(file->path(), makeRelative(*path, file->path()))); } for(std::vector<FileEntry>::iterator it = toAdd.begin(); it != toAdd.end(); ++it) std::cout << it->realPath << " >> " << it->mpqPath << std::endl; HANDLE mpq; if(!SFileCreateArchive(mpqPath.string().c_str(), MPQ_CREATE_ARCHIVE_V2, toAdd.size(), &mpq)) throw std::runtime_error("couldn't create mpq"); SFileSetLocale(0); size_t counter(0); for(std::vector<FileEntry>::iterator it = toAdd.begin(); it != toAdd.end(); ++it) { if(!SFileAddFileEx(mpq, it->realPath.string().c_str(), it->mpqPath.string().c_str(), 0, 0, 0)) std::cout << "couldn't add file " << it->realPath << std::endl; loadbar(toAdd.size(), ++counter); } std::cout << "Compressing mpq" << std::endl; SFileCompactArchive(mpq, NULL, false); SFileFlushArchive(mpq); SFileCloseArchive(mpq); return 0; } catch (const std::exception& e) { std::cerr << "error: " << e.what() << "\n"; }
static void check_all_destroyed(){ assert(counter() == 0); if (counter())throw std::exception("Not all EnterExit destroyed"); };