Who did do a mistake with assignments? - visual-c++

With Qt 6.3.1 and MSVC 2019 (16.11.16) the following code crashes in assignment operator:
#include <QHash>
void fillHash( QHash< int, QString > & hash )
{
const auto str = QStringLiteral( "abc" );
for( qsizetype i = 0; i < 99; i += 3 )
hash[ i ] = hash[ i + 1 ] = hash[ i + 2 ] = str;
}
int main()
{
QHash<int, QString> h;
fillHash(h);
return 0;
}
It crashes with the following stack:
1 std::_Atomic_integral<int,4>::operator++ atomic 1587 0x7ff953ee7279
2 QAtomicOps<int>::ref<int> qatomic_cxx11.h 281 0x7ff953ee3c74
3 QBasicAtomicInteger<int>::ref qbasicatomic.h 101 0x7ff953eed687
4 QArrayData::ref qarraydata.h 88 0x7ff953eed6b7
5 QArrayDataPointer<char16_t>::ref qarraydatapointer.h 325 0x7ff953eed652
6 QArrayDataPointer<char16_t>::QArrayDataPointer<char16_t> qarraydatapointer.h 72 0x7ff953ee40cd
7 QArrayDataPointer<char16_t>::operator= qarraydatapointer.h 93 0x7ff9541ca864
8 QString::operator= qstring.cpp 2825 0x7ff95422d891
9 fillHash main.cpp 9 0x7ff67d9c2d03
10 main main.cpp 18 0x7ff67d9c2dcc
11 invoke_main exe_common.inl 79 0x7ff67d9ca109
12 __scrt_common_main_seh exe_common.inl 288 0x7ff67d9c9fee
13 __scrt_common_main exe_common.inl 331 0x7ff67d9c9eae
14 mainCRTStartup exe_main.cpp 17 0x7ff67d9ca19e
15 BaseThreadInitThunk KERNEL32 0x7ff9b38c7034
16 RtlUserThreadStart ntdll 0x7ff9b4e62651
What's wrong?

Related

SwiftUI/CoreData: Simultaneous accesses to 0x7f92efc61cb8, but modification requires exclusive access

I'm working on an iOS app using SwiftUI and CoreData and am running into a problem that I cannot seem to figure out.
To provide a little bit of information of what I am trying to do:
I have two CoreData entities that have a One-To-Many relationship:
Tarantula - A tarantula may molt many times (To Many) and when deleted, all of the molts shold also be removed (Cascade)
Molt - A molt belongs to a single Tarantula (To One) and when deleted, should have the reference removed from the Tarantula (Nullify)
I then have a view that lists all of the molts for a given Tarantula that allows adding and deleting molts. It looks like this:
struct MoltListView: View {
private static let DATE_FORMATTER: DateFormatter = {
let d = DateFormatter()
d.dateFormat = "MMM d, y"
return d
}()
#Environment(\.managedObjectContext) private var viewContext
#ObservedObject private var tarantula: Tarantula
#FetchRequest private var molts: FetchedResults<Molt>
#State private var userMessage: String = ""
#State private var displayMessage: Bool = false
init(tarantula: Tarantula) {
self.tarantula = tarantula
self._molts = FetchRequest(entity: Molt.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Molt.date, ascending: false)],
predicate: NSPredicate(format: "tarantula = %#", tarantula))
}
var body: some View {
List {
Section(header: Text("Summary")) {
Text("\(molts.count) Molt\(molts.count == 1 ? "" : "s")")
}
Section(header: Text("Molts")) {
NavigationLink(destination: MoltView(tarantula: tarantula, molt: Molt.newModel())) {
Text("Add Molt").foregroundColor(.blue)
}
ForEach(molts, id: \.self) { molt in
NavigationLink(destination: MoltView(tarantula: tarantula, molt: molt)) {
Text(MoltListView.DATE_FORMATTER.string(from: molt.modelDate))
}
}
.onDelete(perform: deleteItems)
}
}.alert(isPresented: $displayMessage) {
Alert(title: Text("Save Failure"), message: Text(userMessage), dismissButton: .default(Text("Ok")))
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { molts[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
viewContext.rollback()
userMessage = "\(error): \(error.localizedDescription)"
displayMessage.toggle()
}
}
}
}
The error I am experiencing comes from whenever I try to delete a molt from the list view. The app instantly crashes and the error is:
Simultaneous accesses to 0x7ffb68d2c518, but modification requires exclusive access.
Previous access (a modification) started at SwiftUI`closure #2 in ListCoreCoordinator.tableView(_:commit:forRowAt:) + 53 (0x7fff56544a85).
Current access (a read) started at:
0 libswiftCore.dylib 0x00007fff2f41fe90 swift_beginAccess + 568
1 SwiftUI 0x00007fff56540670 ListCoreCoordinator.dataSource.getter + 50
2 SwiftUI 0x00007fff56541140 ListCoreCoordinator.updateUITableView(_:to:transaction:) + 608
3 SwiftUI 0x00007fff5653ff40 ListRepresentable.updateUIView(_:context:) + 892
4 SwiftUI 0x00007fff569acc60 PlatformViewRepresentableAdaptor.updateViewProvider(_:context:) + 263
5 SwiftUI 0x00007fff565e8ac0 closure #1 in closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 229
6 SwiftUI 0x00007fff565e89a0 closure #1 in closure #4 in closure #1 in PlatformViewChild.updateValue() + 195
7 SwiftUI 0x00007fff56899b40 ViewRendererHost.performExternalUpdate(_:) + 186
8 SwiftUI 0x00007fff565e8930 closure #4 in closure #1 in PlatformViewChild.updateValue() + 73
9 SwiftUI 0x00007fff565e71e0 closure #1 in PlatformViewChild.updateValue() + 2363
10 SwiftUI 0x00007fff565e6c40 PlatformViewChild.updateValue() + 650
11 SwiftUI 0x00007fff562fa640 partial apply for implicit closure #2 in implicit closure #1 in closure #1 in closure #1 in Attribute.init<A>(_:) + 26
12 AttributeGraph 0x00007fff4be8952a AG::Graph::UpdateStack::update() + 505
13 AttributeGraph 0x00007fff4be89a6a AG::Graph::update_attribute(AG::data::ptr<AG::Node>, bool) + 335
14 AttributeGraph 0x00007fff4be91884 AG::Subgraph::update(unsigned int) + 781
15 SwiftUI 0x00007fff5693a5f0 GraphHost.runTransaction() + 186
16 SwiftUI 0x00007fff5693e110 GraphHost.runTransaction(_:) + 79
17 SwiftUI 0x00007fff5693cba0 GraphHost.flushTransactions() + 211
18 SwiftUI 0x00007fff5693bd40 specialized GraphHost.asyncTransaction<A>(_:mutation:style:) + 464
19 SwiftUI 0x00007fff56509ac0 AttributeInvalidatingSubscriber.invalidateAttribute() + 236
20 SwiftUI 0x00007fff56509a40 AttributeInvalidatingSubscriber.receive(_:) + 105
21 SwiftUI 0x00007fff5650a0d0 protocol witness for Subscriber.receive(_:) in conformance AttributeInvalidatingSubscriber<A> + 16
22 SwiftUI 0x00007fff5669a7e0 SubscriptionLifetime.Connection.receive(_:) + 89
23 Combine 0x00007fff4ab32ec0 ObservableObjectPublisher.Inner.send() + 122
24 Combine 0x00007fff4ab324b0 ObservableObjectPublisher.send() + 801
25 libswiftCoreData.dylib 0x00007fff53ebc900 #objc NSManagedObject._willChange_Swift_Trampoline() + 114
26 CoreData 0x00007fff251b7e4f -[NSManagedObjectContext _postObjectsDidChangeNotificationWithUserInfo:] + 773
27 CoreData 0x00007fff251c6b5b -[NSManagedObjectContext _createAndPostChangeNotification:deletions:updates:refreshes:deferrals:wasMerge:] + 1825
28 CoreData 0x00007fff251b8c0d -[NSManagedObjectContext _processRecentChanges:] + 1041
29 CoreData 0x00007fff2511c241 -[NSManagedObjectContext save:] + 356
30 Tarantulas 0x0000000101a14060 closure #1 in MoltListView.deleteItems(offsets:) + 1165
31 Tarantulas 0x0000000101a07080 thunk for #callee_guaranteed () -> (#error #owned Error) + 15
32 Tarantulas 0x0000000101a16b80 partial apply for thunk for #callee_guaranteed () -> (#error #owned Error) + 20
33 SwiftUI 0x00007fff569b77e0 closure #1 in withTransaction<A>(_:_:) + 83
34 SwiftUI 0x00007fff569b7860 partial apply for closure #1 in withTransaction<A>(_:_:) + 25
35 libswiftCore.dylib 0x00007fff2f22b160 withExtendedLifetime<A, B>(_:_:) + 12
36 SwiftUI 0x00007fff569b7690 withTransaction<A>(_:_:) + 66
37 SwiftUI 0x00007fff569b7580 withAnimation<A>(_:_:) + 140
38 Tarantulas 0x0000000101a13720 MoltListView.deleteItems(offsets:) + 375
39 Tarantulas 0x0000000101a136e0 implicit closure #2 in implicit closure #1 in closure #2 in closure #1 in MoltListView.body.getter + 42
40 SwiftUI 0x00007fff560c0700 partial apply for thunk for #escaping #callee_guaranteed (#in_guaranteed IndexSet) -> () + 17
41 SwiftUI 0x00007fff56713c50 partial apply for thunk for #escaping #callee_guaranteed (#in_guaranteed IndexSet) -> (#out ()) + 17
42 SwiftUI 0x00007fff560c0890 DeleteInteraction.delete() + 125
43 SwiftUI 0x00007fff564a0090 SystemListDataSource.deleteCell(forRowAt:) + 64
44 SwiftUI 0x00007fff56660d40 ShadowListDataSource.commitUpdates() + 963
45 SwiftUI 0x00007fff56544a50 closure #2 in ListCoreCoordinator.tableView(_:commit:forRowAt:) + 76
46 SwiftUI 0x00007fff56544730 ListCoreCoordinator.tableView(_:commit:forRowAt:) + 455
47 SwiftUI 0x00007fff56544ab0 #objc ListCoreCoordinator.tableView(_:commit:forRowAt:) + 131
48 UIKitCore 0x00007fff248ade86 -[UITableView _animateDeletionOfRowAtIndexPath:] + 188
49 UIKitCore 0x00007fff248b68d7 __82-[UITableView _contextualActionForDeletingRowAtIndexPath:usingPresentationValues:]_block_invoke + 60
50 UIKitCore 0x00007fff247fe817 -[UIContextualAction executeHandlerWithView:completionHandler:] + 148
51 UIKitCore 0x00007fff2480c7b4 -[UISwipeOccurrence _executeLifecycleForPerformedAction:sourceView:completionHandler:] + 656
52 UIKitCore 0x00007fff2480cf2d -[UISwipeOccurrence _performSwipeAction:inPullView:swipeInfo:] + 621
53 UIKitCore 0x00007fff2480ec53 -[UISwipeOccurrence swipeActionPullView:tappedAction:] + 92
54 UIKitCore 0x00007fff24816a96 -[UISwipeActionPullView _tappedButton:] + 148
55 UIKitCore 0x00007fff2467b5db -[UIApplication sendAction:to:from:forEvent:] + 83
56 UIKitCore 0x00007fff23fa488d -[UIControl sendAction:to:forEvent:] + 223
57 UIKitCore 0x00007fff23fa4b43 -[UIControl _sendActionsForEvents:withEvent:] + 332
58 UIKitCore 0x00007fff23fa3384 -[UIControl touchesEnded:withEvent:] + 500
59 UIKitCore 0x00007fff241a546a _UIGestureEnvironmentUpdate + 8849
60 UIKitCore 0x00007fff241a4c77 -[UIGestureEnvironment _updateForEvent:window:] + 887
61 UIKitCore 0x00007fff246b893d -[UIWindow sendEvent:] + 4752
62 UIKitCore 0x00007fff2469367d -[UIApplication sendEvent:] + 633
63 UIKitCore 0x00007fff24720d55 __processEventQueue + 13895
64 UIKitCore 0x00007fff2471aca7 __eventFetcherSourceCallback + 104
65 CoreFoundation 0x00007fff2038c369 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
66 CoreFoundation 0x00007fff2038c1be __CFRunLoopDoSource0 + 180
67 CoreFoundation 0x00007fff2038b65c __CFRunLoopDoSources0 + 248
68 CoreFoundation 0x00007fff20385bb1 __CFRunLoopRun + 878
69 CoreFoundation 0x00007fff2038548f CFRunLoopRunSpecific + 567
70 GraphicsServices 0x00007fff2b76ad28 GSEventRunModal + 139
71 UIKitCore 0x00007fff24674df7 -[UIApplication _run] + 912
72 UIKitCore 0x00007fff24679fd3 UIApplicationMain + 101
73 SwiftUI 0x00007fff568cfc60 closure #1 in KitRendererCommon(_:) + 119
74 SwiftUI 0x00007fff568cfbc0 runApp<A>(_:) + 143
75 SwiftUI 0x00007fff56407980 static App.main() + 61
76 Tarantulas 0x0000000101a17940 static TarantulasApp.$main() + 33
77 Tarantulas 0x0000000101a17c20 main + 20
78 libdyld.dylib 0x00007fff20256408 start + 1
The only way I have been able to prevent this error is to remove the delete rule on the Molt->Tarantula relationship from Nullify to No Action. However, this seems more like hack to me instead of a fix.
I was wondering if anyone may have experienced this issue before or may be able to help me in resolving it.
This issue has been confirmed to be due to a system bug.
The workaround is to wrap the delete logic in NSManagedObjectContext.perform. For example:
private func deleteItems(offsets: IndexSet) {
withAnimation {
viewContext.perform { // HERE
offsets.map { molts[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
viewContext.rollback()
userMessage = "\(error): \(error.localizedDescription)"
displayMessage.toggle()
}
}
}
}
For reference, here is the Apple Developer Forum post related to this issue: https://developer.apple.com/forums/thread/668299

Send array to function in BACI (C--)

I want to send an array to a function then print all of the elements. I have an error.
.LST file is:
BACI System: C-- to PCODE Compiler, 16:59 27 Oct 2005
Source file: 1.cm Fri Nov 01 03:16:20 2019
line pc
1 0
2 0
3 0
4 0 void Print(int a[])
Error near '[', line 4 of file 1.cm:
** syntax error
Because of 1 error the PCODE file will not execute
Baci reference is:
http://inside.mines.edu/~tcamp/baci/baci_index.html
C:\badosxe> bacc 1.cm Error near '[', line 4 of file 1.cm: ** syntax error>>Because of 1 error the PCODE file will not execute Pcode and tables are stored in 1.pco Compilation listing is stored in 1.lst
void Print(int a[])
{
int i;
for (i = 0; i < 5; i = i + 1)
{
cout<<a[i];
}
}
main()
{
cout << endl;
cobegin
{
int a[5] = {1,2,3,4,5};
Print(a);
}
}

Unable to understand the boost::mutex error C++

I am new to multithreading and I have used the thread pool mechanism to synchronize interactions amongst two classes.
While compiling i am unable to understand the error.
The classes are as below:
InstrumentProcessor.h
1 #ifndef INSTRUMENTPROCESSOR_H
2 #define INSTRUMENTPROCESSOR_H
3
4 #include <boost/thread/thread.hpp>
5 #include <boost/thread/mutex.hpp>
6 #include <boost/algorithm/string.hpp>
7 #include <boost/lexical_cast.hpp>
8 #include "Semaphore.h"
9 #include "Instrument.h"
10 #include <queue>
11 #include <string>
12 #include <vector>
13
14
15 class InstrumentProcessor
16 {
17 public:
18 InstrumentProcessor(unsigned int const numThreads);
19 ~InstrumentProcessor();
20 bool Start();
21 bool Stop();
22 void AddLine(const std::string& LineRead); // Producer
23
24 private:
25 void Process(); // Worker Function
26 void ProcessLine(std::string& line); // Consumer
27
28 private:
29 unsigned int const numThreads_;
30 boost::mutex ProcessorMutex_;
31 boost::thread_group ProcessorGroup_;
32 Semaphore taskCount_;
33 std::queue<std::string> Line_;
34 bool stop_;
35 std::vector<std::string> elements_;
36 std::vector<Instrument> Instruments_;
37 };
38
39 #endif /* INSTRUMENTPROCESSOR_H */
InstrumentProcessor.cpp
1 #include "InstrumentProcessor.h"
2
3 InstrumentProcessor::InstrumentProcessor(unsigned int const numThreads)
4 : numThreads_(numThreads), stop_(false)
5 {
6 Instruments_.reserve(25);
7 }
8
9 InstrumentProcessor::~InstrumentProcessor()
10 {
11
12 }
13
14 bool InstrumentProcessor::Start()
15 {
16 std::cout << "\nParallel Processing Started ...." << std::endl;
17 for(unsigned int i=0; i<numThreads_; i++)
18 {
19 ProcessorGroup_.create_thread(boost::bind(&InstrumentProcessor ::Process, this));
20 }
21
22 return true;
23 }
24
25 bool InstrumentProcessor::Stop()
26 {
27 stop_ = true;
28 ProcessorGroup_.join_all();
29 std::cout << "\n Parallel Processing Stopped ...." << std::endl;
30 return stop_;
31 }
32
33
34 void InstrumentProcessor::Process()
35 {
36 while(!stop_)
37 {
38 --taskCount_;
39 std::string currentLine;
40 {
41 boost::mutex::scoped_lock lock(ProcessorMutex_);
42 currentLine = Line_.front();
43 Line_.pop();
44 }
45 ProcessLine(currentLine);
46 }
47 }
48
49 void InstrumentProcessor::AddLine(const std::string& LineRead)
50 {
51 boost::mutex::scoped_lock lock(ProcessorMutex_);
52 Line_.push(LineRead);
53 ++taskCount_;
54 }
55
56 void InstrumentProcessor::ProcessLine(std::string& line)
57 {
58 boost::algorithm::split(elements_, line, boost::is_any_of("\t "), boos t::token_compress_on);
59 for(unsigned int i=1; i<elements_.size(); i++)
60 {
61 if (elements_[i].compare("nan") == 0)
62 continue;
63 else
64 {
65 double data = boost::lexical_cast<double>(elements_[i] );
66 Instruments_[i-1].CleanData(data); // This function makes a call to the Insrument Class member function
67 }
68 }
69 }
Instrument.h
1 #ifndef INSTRUMENT_H
2 #define INSTRUMENT_H
3
4 #include <iostream>
5 #include <boost/thread/mutex.hpp>
6 #include <cmath>
7
8 class Instrument
9 {
10 public:
11 Instrument();
12 ~Instrument();
13 bool PopulateData(double& data);
14 bool CleanData(double& data);
15 bool PrintData();
16
17 private:
18 bool getMeanAndStandardDeviation();
19
20 private:
21 double data_;
22 int N_;
23 double Mean_;
24 double M2_;
25 double stdDev_;
26 double InitialValue_;
27 bool Init_;
28 boost::mutex InstrumentMutex_;
29 };
30
31 #endif /* INSTRUMENT_H */
Instrument.cpp
1 #include "Instrument.h"
2
3 Instrument::Instrument()
4 : Init_(false), data_(0.0), Mean_(0.0), stdDev_(0.0), InitialValue_(0.0), N_(0 ), M2_(0.0)
5 {
6
7 }
8
9 Instrument::~Instrument()
10 {
11
12 }
13
14 bool Instrument::PopulateData(double& data)
15 {
16 data_ = data;
17 if(!Init_)
18 {
19 InitialValue_ = data_;
20 Init_ = true;
21 std::cout << "The initial value is: " << InitialValue_ << std: :endl;
22 }
23 return true;
24 }
25
26 /* Cleaning Part 2:
27 * Each data point will be represented as the % change from the initial value.
28 * This will then be added by 101 so as to get uniform positive value with the
29 * origin of the data shifted to init_origin + 101
30 */
31
32 bool Instrument::CleanData(double& data)
33 {
34
35 std::cout << "\nData begin inserted: " << data << std::endl;
36 boost::mutex::scoped_lock lock(InstrumentMutex_);
37 PopulateData(data);
38 data_ = ((data_-InitialValue_)/InitialValue_)*100;
39 data_ += 101;
40 getMeanAndStandardDeviation();
41 return true;
42 }
43
44 // Welford recurrence relation for tick based mean and standard deviation calc ulation
45 bool Instrument::getMeanAndStandardDeviation()
46 {
47 ++N_;
48 double delta = data_ - Mean_;
49 Mean_ += delta/N_;
50 M2_ += delta*(data_ - Mean_);
51
52 if(N_ >= 2)
53 {
54 double variance = M2_/(N_-1);
55 stdDev_ = std::sqrt(variance);
56 }
57 return true;
58 }
59
60 bool Instrument::PrintData()
61 {
62 std::cout << "\nMean: " << Mean_ << "Std Dev: " << stdDev_ << std::end l;
63 return true;
64 }
I am compiling the above with the following compilation line:
g++ -std=c++11 -I /usr/lib/x86_64-linux-gnu -lboost_thread -c InstrumentProcessor.cpp
which yields in the below error.
In file included from /usr/include/c++/4.8/memory:64:0,
from /usr/include/boost/config/no_tr1/memory.hpp:21,
from /usr/include/boost/smart_ptr/shared_ptr.hpp:27,
from /usr/include/boost/shared_ptr.hpp:17,
from /usr/include/boost/date_time/time_clock.hpp:17,
from /usr/include/boost/thread/thread_time.hpp:9,
from /usr/include/boost/thread/lock_types.hpp:18,
from /usr/include/boost/thread/pthread/thread_data.hpp:12,
from /usr/include/boost/thread/thread_only.hpp:17,
from /usr/include/boost/thread/thread.hpp:12,
from InstrumentProcessor.h:4,
from InstrumentProcessor.cpp:1:
/usr/include/c++/4.8/bits/stl_construct.h: In instantiation of ‘void std::_Construct(_T1*, _Args&& ...) [with _T1 = Instrument; _Args = {Instrument}]’:
/usr/include/c++/4.8/bits/stl_uninitialized.h:75:53: required from ‘static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*; bool _TrivialValueTypes = false]’
/usr/include/c++/4.8/bits/stl_uninitialized.h:117:41: required from ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*]’
/usr/include/c++/4.8/bits/stl_uninitialized.h:258:63: required from ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::move_iterator<Instrument*>; _ForwardIterator = Instrument*; _Tp = Instrument]’
/usr/include/c++/4.8/bits/stl_vector.h:1142:29: required from ‘std::vector<_Tp, _Alloc>::pointer std::vector<_Tp, _Alloc>::_M_allocate_and_copy(std::vector<_Tp, _Alloc>::size_type, _ForwardIterator, _ForwardIterator) [with _ForwardIterator = std::move_iterator<Instrument*>; _Tp = Instrument; _Alloc = std::allocator<Instrument>; std::vector<_Tp, _Alloc>::pointer = Instrument*; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
/usr/include/c++/4.8/bits/vector.tcc:75:70: required from ‘void std::vector<_Tp, _Alloc>::reserve(std::vector<_Tp, _Alloc>::size_type) [with _Tp = Instrument; _Alloc = std::allocator<Instrument>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]’
InstrumentProcessor.cpp:6:25: required from here
/usr/include/c++/4.8/bits/stl_construct.h:75:7: error: use of deleted function ‘Instrument::Instrument(const Instrument&)’
{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
^
In file included from InstrumentProcessor.h:9:0,
from InstrumentProcessor.cpp:1:
Instrument.h:8:7: note: ‘Instrument::Instrument(const Instrument&)’ is implicitly deleted because the default definition would be ill-formed:
class Instrument
^
Instrument.h:8:7: error: use of deleted function ‘boost::mutex::mutex(const boost::mutex&)’
In file included from /usr/include/boost/thread/lock_guard.hpp:11:0,
from /usr/include/boost/thread/pthread/thread_data.hpp:11,
from /usr/include/boost/thread/thread_only.hpp:17,
from /usr/include/boost/thread/thread.hpp:12,
from InstrumentProcessor.h:4,
from InstrumentProcessor.cpp:1:
/usr/include/boost/thread/pthread/mutex.hpp:96:9: error: declared here
BOOST_THREAD_NO_COPYABLE(mutex)
^
Any help on this will be appreciated.
Implementation of method vector::reserve() requires either move-constructor or copy-constructor from Instrument class.
But both of these constructors may not generated for the class automatically, because its member InstrumentMutex_ is neither copiable nor movable (mutexes can neither be copied nor moved).
You need to declare move-constructor for Instrument class manually for possibility to use it in vector operations. Becauase of mutex member, this won't be true move-constructor (mutex cannot be moved), but simple initializing of mutex is sufficient for given usage.
Alternatively, instead of calling .reserve() method after creating the vector _Instruments, you may initialize this vector with precise size:
InstrumentProcessor::InstrumentProcessor(unsigned int const numThreads)
: numThreads_(numThreads), stop_(false), _Instruments(25)
{
}
This initialization requires only default constructor from Instrument class, which is already declared.
Sized vector constructor differs from .reserve() in that all vector's elements are created (as opposite to allocated), which may be not suitable for your case. But if creation of all elements is OK, then this initialization should be preffered for previous one, because it avoids definition of move-constructor without well-defined semantic (mutex member are not moved but recreated).

Rounding error in Rust trying to create CORDIC table for sin function

I am trying to implement the CORDIC method in rust using this c implementation as an example, however i am having rounding error issues when generating the table. Here is my code and the results.
fn generate_table () {
let pi: f32 = 3.1415926536897932384626;
let k1: f32 = 0.6072529350088812561694; // 1/k
let num_bits: uint = 32;
let num_elms: uint = num_bits;
let mul: f32 = 1073741824.000000; // 1<<(bits-2)
println!("Cordic sin in rust");
println!("num bits {}", num_bits);
println!("mul {}", mul);
println!("pi is {}", pi);
println!("k1 is {}", k1);
let shift: f32 = 2.0;
for ii in range(0, num_bits) {
let ipow: f32 = 1f32/shift.powi(ii as i32);
let cur: f32 = ipow.atan() * mul;
//println!("table values {:.10f}", cur);
println!("table values 0x{}", std::f32::to_str_hex(cur));
}
}
fn main() {
generate_table();
}
which gives me the following table, notice the first and last values to see the biggest errors.
table values 0x3243f6c0
table values 0x1dac6700
table values 0xfadbb00
table values 0x7f56ea8
table values 0x3feab78
table values 0x1ffd55c
table values 0xfffaab
table values 0x7fff55.8
table values 0x3fffea.c
table values 0x1ffffd.6
table values 0xfffff.b
table values 0x7ffff.f8
table values 0x40000
table values 0x20000
table values 0x10000
table values 0x8000
table values 0x4000
table values 0x2000
table values 0x1000
table values 0x800
table values 0x400
table values 0x200
table values 0x100
table values 0x80
table values 0x40
table values 0x20
table values 0x10
table values 0x8
table values 0x4
table values 0x2
table values 0x1
table values 0x0.8
Why am i getting these (rounding?) errors and how do i fix them?
The quick answer: How certain are you that you are feeding identical inputs into both computations? In particular, the C implementation you quote says:
int mul = (1<<(bits-2));
while you have hard-coded:
let mul: f32 = 1073741824.000000; // 1<<(bits-2)
Note 1: You have changed the type of mul from an int to an f32.
Note 2: In the output I get when I run your program, I see this:
mul 1073741844
Notably, this is different from the hard-coded constant you wrote above; it is off by 20.
My usual way to debug a problem like this, and that I actually did in this case before I noticed the problem above, is to instrument both the C and the Rust versions of the code with printouts of the values of each intermediate expression, in order to identify where things start to differ and therefore narrow down which operation is introducing an "error."
In this case, it involved modifying the C code and the Rust code in parallel to print out a table of not just the i (or ii in the Rust version) and the output c, but also every intermediate result.
Here is the code for each of those, along with the output tables I got in the end. (But then it was only analyzing those tables that I realized that the two mul values differed!)
C code:
#include <stdio.h>
#include <math.h>
#define PI 3.1415926536897932384626
#define K1 0.6072529350088812561694
int main(int argc, char **argv)
{
int i;
int bits = 32; // number of bits
int mul = (1<<(bits-2));
int n = bits; // number of elements.
int c;
printf("Cordic sin in C\n");
printf("num bits %d\n", bits);
printf("mul %d\n", mul);
printf("pi is %g\n", PI);
printf("k1 is %g\n", K1);
float shift = 2.0;
printf("computing c = atan(pow(2, -i)) * mul\n");
printf(" i \t c p a c2\n");
for(i=0;i<n;i++)
{
c = (atan(pow(2, -i)) * mul);
int neg_i = -i;
double p = pow(2, neg_i);
double a = atan(p);
int c2 = a * mul;;
printf("% 8d \t 0x%08X % 12g % 12g 0x%08X\n", i, c, p, a, c2);
}
}
Rust code:
fn generate_table () {
let pi: f32 = 3.1415926536897932384626;
let k1: f32 = 0.6072529350088812561694; // 1/k
let num_bits: uint = 32;
let num_elms: uint = num_bits;
let mul: f32 = 1073741824.000000; // 1<<(bits-2)
println!("Cordic sin in rust");
println!("num bits {}", num_bits);
println!("mul {}", mul);
println!("1 << (bits - 2): {}", (1i << (num_bits-2)) as f32);
println!("pi is {}", pi);
println!("k1 is {}", k1);
let shift: f32 = 2.0;
println!("computing c = (1f32/shift.powi(ii as i32)).atan() * mul");
println!(" i \t c p a c2\n");
for ii in range(0, num_bits) {
let ipow: f32 = 1f32/shift.powi(ii as i32);
let cur: f32 = ipow.atan() * mul;
let a = ipow.atan();
let c2 = a * mul;
//println!("table values {:.10f}", cur);
// println!("table values 0x{}", std::f32::to_str_hex(cur));
println!("{:8u} \t 0x{:8s} {:12f} {:12f} 0x{:8s}",
ii,
std::f32::to_str_hex(cur),
ipow,
a,
std::f32::to_str_hex(c2),
);
}
}
fn main() {
generate_table();
}
Tables generated:
% gcc gentable2.c && ./a.out
Cordic sin in C
num bits 32
mul 1073741824
pi is 3.14159
k1 is 0.607253
computing c = atan(pow(2, -i)) * mul
i c p a c2
0 0x3243F6A8 1 0.785398 0x3243F6A8
1 0x1DAC6705 0.5 0.463648 0x1DAC6705
2 0x0FADBAFC 0.25 0.244979 0x0FADBAFC
3 0x07F56EA6 0.125 0.124355 0x07F56EA6
4 0x03FEAB76 0.0625 0.0624188 0x03FEAB76
5 0x01FFD55B 0.03125 0.0312398 0x01FFD55B
6 0x00FFFAAA 0.015625 0.0156237 0x00FFFAAA
7 0x007FFF55 0.0078125 0.00781234 0x007FFF55
8 0x003FFFEA 0.00390625 0.00390623 0x003FFFEA
9 0x001FFFFD 0.00195312 0.00195312 0x001FFFFD
10 0x000FFFFF 0.000976562 0.000976562 0x000FFFFF
11 0x0007FFFF 0.000488281 0.000488281 0x0007FFFF
12 0x0003FFFF 0.000244141 0.000244141 0x0003FFFF
13 0x0001FFFF 0.00012207 0.00012207 0x0001FFFF
14 0x0000FFFF 6.10352e-05 6.10352e-05 0x0000FFFF
15 0x00007FFF 3.05176e-05 3.05176e-05 0x00007FFF
16 0x00003FFF 1.52588e-05 1.52588e-05 0x00003FFF
17 0x00001FFF 7.62939e-06 7.62939e-06 0x00001FFF
18 0x00000FFF 3.8147e-06 3.8147e-06 0x00000FFF
19 0x000007FF 1.90735e-06 1.90735e-06 0x000007FF
20 0x000003FF 9.53674e-07 9.53674e-07 0x000003FF
21 0x000001FF 4.76837e-07 4.76837e-07 0x000001FF
22 0x000000FF 2.38419e-07 2.38419e-07 0x000000FF
23 0x0000007F 1.19209e-07 1.19209e-07 0x0000007F
24 0x0000003F 5.96046e-08 5.96046e-08 0x0000003F
25 0x0000001F 2.98023e-08 2.98023e-08 0x0000001F
26 0x0000000F 1.49012e-08 1.49012e-08 0x0000000F
27 0x00000008 7.45058e-09 7.45058e-09 0x00000008
28 0x00000004 3.72529e-09 3.72529e-09 0x00000004
29 0x00000002 1.86265e-09 1.86265e-09 0x00000002
30 0x00000001 9.31323e-10 9.31323e-10 0x00000001
31 0x00000000 4.65661e-10 4.65661e-10 0x00000000
% rustc gentable.rs && ./gentable
gentable.rs:5:9: 5:17 warning: unused variable: `num_elms`, #[warn(unused_variables)] on by default
gentable.rs:5 let num_elms: uint = num_bits;
^~~~~~~~
Cordic sin in rust
num bits 32
mul 1073741844
1 << (bits - 2): 1073741844
pi is 3.141593
k1 is 0.607253
computing c = (1f32/shift.powi(ii as i32)).atan() * mul
i c p a c2
0 0x3243f6c0 1 0.785398 0x3243f6c0
1 0x1dac6700 0.5 0.463648 0x1dac6700
2 0xfadbb00 0.25 0.244979 0xfadbb00
3 0x7f56ea8 0.125 0.124355 0x7f56ea8
4 0x3feab78 0.0625 0.062419 0x3feab78
5 0x1ffd55c 0.03125 0.03124 0x1ffd55c
6 0xfffaab 0.015625 0.015624 0xfffaab
7 0x7fff55.8 0.007813 0.007812 0x7fff55.8
8 0x3fffea.c 0.003906 0.003906 0x3fffea.c
9 0x1ffffd.6 0.001953 0.001953 0x1ffffd.6
10 0xfffff.b 0.000977 0.000977 0xfffff.b
11 0x7ffff.f8 0.000488 0.000488 0x7ffff.f8
12 0x40000 0.000244 0.000244 0x40000
13 0x20000 0.000122 0.000122 0x20000
14 0x10000 0.000061 0.000061 0x10000
15 0x8000 0.000031 0.000031 0x8000
16 0x4000 0.000015 0.000015 0x4000
17 0x2000 0.000008 0.000008 0x2000
18 0x1000 0.000004 0.000004 0x1000
19 0x800 0.000002 0.000002 0x800
20 0x400 0.000001 0.000001 0x400
21 0x200 0 0 0x200
22 0x100 0 0 0x100
23 0x80 0 0 0x80
24 0x40 0 0 0x40
25 0x20 0 0 0x20
26 0x10 0 0 0x10
27 0x8 0 0 0x8
28 0x4 0 0 0x4
29 0x2 0 0 0x2
30 0x1 0 0 0x1
31 0x0.8 0 0 0x0.8
%

Inserting an NSManagedObject in Swift with a To-One Relationship

I'm having trouble simply inserting an NSManagedObject with a to-one relationship when using Swift on Xcode 6b3.
I put my repro on GitHub but the failing code (in SwiftCoreDataRelationshipReproTests.swift's testSwiftToOne unit test method) boils down to this:
let momURL : NSURL = NSBundle.mainBundle().URLForResource("SwiftCoreDataRelationshipRepro",
withExtension: "momd")
let mom : NSManagedObjectModel = NSManagedObjectModel(contentsOfURL: momURL)
let psc : NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: mom);
let ps : NSPersistentStore = psc.addPersistentStoreWithType(
NSInMemoryStoreType,
configuration: nil,
URL: nil,
options: nil,
error: nil)
let moc : NSManagedObjectContext = NSManagedObjectContext()
moc.persistentStoreCoordinator = psc
// This throws an NSInvalidArgumentException: "An NSManagedObject of class 'NSManagedObject' must have a valid NSEntityDescription."
NSManagedObject(
entity: NSEntityDescription.entityForName("Pet", inManagedObjectContext: moc),
insertIntoManagedObjectContext: moc)
That seems like it should work. Nothing tricky.
My very similar Person entity with a to-many relationship can be inserted (and saved) correctly with Swift (as evidenced in the passing testSwiftToMany test) . The more-complicated Objective-C version also succeeds with the same data model (the passing testObjcToOneAndToMany test).
Here's the entire exception:
file:///%3Cunknown%3E: test failure: -[SwiftCoreDataRelationshipReproTests testSwiftToOne()] failed: failed: caught "NSInvalidArgumentException", "An NSManagedObject of class 'NSManagedObject' must have a valid NSEntityDescription."
(
0 CoreFoundation 0x00007fff8dd6525c __exceptionPreprocess + 172
1 libobjc.A.dylib 0x00007fff84ce5e75 objc_exception_throw + 43
2 CoreData 0x00007fff8765dd16 -[NSManagedObject initWithEntity:insertIntoManagedObjectContext:] + 550
3 SwiftCoreDataRelationshipReproTests 0x0000000100394d4a _TTOFCSo15NSManagedObjectcfMS_FT6entityGSQCSo19NSEntityDescription_30insertIntoManagedObjectContextGSQCSo22NSManagedObjectContext__S_ + 42
4 SwiftCoreDataRelationshipReproTests 0x00000001003946bd _TFCSo15NSManagedObjectCfMS_FT6entityGSQCSo19NSEntityDescription_30insertIntoManagedObjectContextGSQCSo22NSManagedObjectContext__S_ + 93
5 SwiftCoreDataRelationshipReproTests 0x0000000100393450 _TFC35SwiftCoreDataRelationshipReproTests35SwiftCoreDataRelationshipReproTests14testSwiftToOnefS0_FT_T_ + 816
6 SwiftCoreDataRelationshipReproTests 0x00000001003934c2 _TToFC35SwiftCoreDataRelationshipReproTests35SwiftCoreDataRelationshipReproTests14testSwiftToOnefS0_FT_T_ + 34
7 CoreFoundation 0x00007fff8dc50a5c __invoking___ + 140
8 CoreFoundation 0x00007fff8dc508c4 -[NSInvocation invoke] + 308
9 XCTest 0x00000001003b023a -[XCTestCase invokeTest] + 253
10 XCTest 0x00000001003b03ac -[XCTestCase performTest:] + 142
11 XCTest 0x00000001003b8ad0 -[XCTest run] + 257
12 XCTest 0x00000001003af68b -[XCTestSuite performTest:] + 379
13 XCTest 0x00000001003b8ad0 -[XCTest run] + 257
14 XCTest 0x00000001003af68b -[XCTestSuite performTest:] + 379
15 XCTest 0x00000001003b8ad0 -[XCTest run] + 257
16 XCTest 0x00000001003af68b -[XCTestSuite performTest:] + 379
17 XCTest 0x00000001003b8ad0 -[XCTest run] + 257
18 XCTest 0x00000001003acc8f __25-[XCTestDriver _runSuite]_block_invoke + 56
19 XCTest 0x00000001003b773d -[XCTestObservationCenter _observeTestExecutionForBlock:] + 162
20 XCTest 0x00000001003acbc8 -[XCTestDriver _runSuite] + 269
21 XCTest 0x00000001003ad34a -[XCTestDriver _checkForTestManager] + 551
22 XCTest 0x00000001003bb879 +[XCTestProbe runTests:] + 175
23 Foundation 0x00007fff8e0aacb7 __NSFireDelayedPerform + 333
24 CoreFoundation 0x00007fff8dccc494 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 20
25 CoreFoundation 0x00007fff8dccbfcf __CFRunLoopDoTimer + 1151
26 CoreFoundation 0x00007fff8dd3d5aa __CFRunLoopDoTimers + 298
27 CoreFoundation 0x00007fff8dc87755 __CFRunLoopRun + 1525
28 CoreFoundation 0x00007fff8dc86f25 CFRunLoopRunSpecific + 309
29 HIToolbox 0x00007fff8e566a0d RunCurrentEventLoopInMode + 226
30 HIToolbox 0x00007fff8e566685 ReceiveNextEventCommon + 173
31 HIToolbox 0x00007fff8e5665bc _BlockUntilNextEventMatchingListInModeWithFilter + 65
32 AppKit 0x00007fff8538e26e _DPSNextEvent + 1434
33 AppKit 0x00007fff8538d8bb -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:] + 122
34 AppKit 0x00007fff853819bc -[NSApplication run] + 553
35 AppKit 0x00007fff8536c7a3 NSApplicationMain + 940
36 SwiftCoreDataRelationshipRepro 0x000000010000ad55 top_level_code + 37
37 SwiftCoreDataRelationshipRepro 0x000000010000ad8a main + 42
38 libdyld.dylib 0x00007fff861115fd start + 1
)
So I couldn't solve the problem, but I think I narrowed it down to a bug in the framework or Swift. Using entityForName is equivalent to getting the entity directly out of the managedObjectModel so I tried to do it that way:
let entities = moc.persistentStoreCoordinator.managedObjectModel.entitiesByName;
let keys = Array(entities.keys)
let petVar : String = keys[1] as String
let isEqual1 = (petVar == "Pet") // true
let isEqual2 = (petVar.hashValue == "Pet".hashValue) // true
let result1 = entities["Pet"] // nil
let result2 = entities[petVar] // non-nil
let result3 = entities.bridgeToObjectiveC().objectForKey("Pet".bridgeToObjectiveC()) // nil
let result4 = entities.bridgeToObjectiveC().objectForKey(petVar.bridgeToObjectiveC()) // non-nil
// Doesn't Pass
XCTAssertNotNil(NSEntityDescription.entityForName("Pet", inManagedObjectContext: moc));
// Passes
XCTAssertNotNil(NSEntityDescription.entityForName(petVar, inManagedObjectContext: moc));
It works with the key pulled out of the dictionary but not a string that is equivalent to the key (even the hash values are the same).
I think that this pretty definitely shows that there is a bug either in the framework or in Swift itself. I am running Xcode (6b3) and 10.9.4
I think it is time for a bug report.

Resources